diff --git a/dist/main.js b/dist/main.js index d4e4ae16..ef8e562f 100644 --- a/dist/main.js +++ b/dist/main.js @@ -1 +1 @@ -function xmlToJson(e,t){if(e.nodeType===e.TEXT_NODE){var i=e.nodeValue;if(null===i.match(/^\s+$/))return i}else if(e.nodeType===e.ELEMENT_NODE||e.nodeType===e.DOCUMENT_NODE){var s={type:e.nodeName,children:[]};if(e.nodeType===e.ELEMENT_NODE)for(var r=0;rvoid 0;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)}function loadArraybuffer(e,t,i){var s=e=>void 0;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),s=new Uint8Array(e);for(var a=0;a
Default text
',i.appendChild(this._modal),this._modalVisible=!1,this._modal.style.display="hidden"}show(e){this._modalVisible=!0,this._modal.querySelector(".xeokit-busy-modal-message").innerText=e,this._modal.style.display="block"}hide(){this._modalVisible=!1,this._modal.style.display="none"}destroy(){super.destroy(),this._modal&&(this._modal.parentNode.removeChild(this._modal),this._modal=null)}}const FloatArrayType=Float64Array,tempMat1=new FloatArrayType(16),tempMat2=new FloatArrayType(16),tempVec4=new FloatArrayType(4),math={MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,DEGTORAD:.0174532925,RADTODEG:57.295779513,vec2:e=>new FloatArrayType(e||2),vec3:e=>new FloatArrayType(e||3),vec4:e=>new FloatArrayType(e||4),mat3:e=>new FloatArrayType(e||9),mat3ToMat4:(e,t=new FloatArrayType(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 FloatArrayType(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new Float32Array(2);for(let r=0,o=e.length;r{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(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,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 FloatArrayType(e[0]);for(let i=1;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],a=t[1],n=t[2];return[s*n-r*a,r*o-i*n,i*a-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],a=t[0],n=t[1],l=t[2];return i[0]=r*l-o*n,i[1]=o*a-s*l,i[2]=s*n-r*a,i},sqLenVec4:e=>math.dotVec4(e,e),lenVec4:e=>Math.sqrt(math.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=>math.dotVec3(e,e),sqLenVec2:e=>math.dotVec2(e,e),lenVec3:e=>Math.sqrt(math.sqLenVec3(e)),distVec3:(()=>{const e=new FloatArrayType(3);return(t,i)=>math.lenVec3(math.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(math.sqLenVec2(e)),distVec2:(()=>{const e=new FloatArrayType(2);return(t,i)=>math.lenVec2(math.subVec2(t,i,e))})(),rcpVec3:(e,t)=>math.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/math.lenVec4(e);return math.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/math.lenVec3(e);return math.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/math.lenVec2(e);return math.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=math.dotVec3(e,t)/Math.sqrt(math.sqLenVec3(e)*math.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new FloatArrayType(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=math.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=math.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=math.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({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||new FloatArrayType(3))[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:()=>math.m4s(0),setMat4ToOnes:()=>math.m4s(1),diagonalMat4v:e=>new FloatArrayType([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)=>math.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>math.diagonalMat4c(e,e,e,e),identityMat4:(e=new FloatArrayType(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 FloatArrayType(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)=>math.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],a=e[3],n=e[4],l=e[5],h=e[6],c=e[7],d=e[8],u=e[9],p=e[10],m=e[11],_=e[12],f=e[13],g=e[14],v=e[15],b=t[0],y=t[1],M=t[2],w=t[3],P=t[4],x=t[5],E=t[6],A=t[7],C=t[8],R=t[9],S=t[10],L=t[11],D=t[12],T=t[13],k=t[14],B=t[15];return i[0]=b*s+y*n+M*d+w*_,i[1]=b*r+y*l+M*u+w*f,i[2]=b*o+y*h+M*p+w*g,i[3]=b*a+y*c+M*m+w*v,i[4]=P*s+x*n+E*d+A*_,i[5]=P*r+x*l+E*u+A*f,i[6]=P*o+x*h+E*p+A*g,i[7]=P*a+x*c+E*m+A*v,i[8]=C*s+R*n+S*d+L*_,i[9]=C*r+R*l+S*u+L*f,i[10]=C*o+R*h+S*p+L*g,i[11]=C*a+R*c+S*m+L*v,i[12]=D*s+T*n+k*d+B*_,i[13]=D*r+T*l+k*u+B*f,i[14]=D*o+T*h+k*p+B*g,i[15]=D*a+T*c+k*m+B*v,i},mulMat3(e,t,i){i||(i=new FloatArrayType(9));const s=e[0],r=e[3],o=e[6],a=e[1],n=e[4],l=e[7],h=e[2],c=e[5],d=e[8],u=t[0],p=t[3],m=t[6],_=t[1],f=t[4],g=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*u+r*_+o*v,i[3]=s*p+r*f+o*b,i[6]=s*m+r*g+o*y,i[1]=a*u+n*_+l*v,i[4]=a*p+n*f+l*b,i[7]=a*m+n*g+l*y,i[2]=h*u+c*_+d*v,i[5]=h*p+c*f+d*b,i[8]=h*m+c*g+d*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=math.vec4()){const s=t[0],r=t[1],o=t[2],a=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*a,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*a,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*a,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*a,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],a=e[12],n=e[9];if(!t||e===t){const t=e[1],l=e[2],h=e[3],c=e[6],d=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=a,e[4]=t,e[6]=n,e[7]=o,e[8]=l,e[9]=c,e[11]=s,e[12]=h,e[13]=d,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=a,t[4]=e[1],t[5]=e[5],t[6]=n,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],a=e[5],n=e[6],l=e[7],h=e[8],c=e[9],d=e[10],u=e[11],p=e[12],m=e[13],_=e[14],f=e[15];return p*c*n*r-h*m*n*r-p*a*d*r+o*m*d*r+h*a*_*r-o*c*_*r-p*c*s*l+h*m*s*l+p*i*d*l-t*m*d*l-h*i*_*l+t*c*_*l+p*a*s*u-o*m*s*u-p*i*n*u+t*m*n*u+o*i*_*u-t*a*_*u-h*a*s*f+o*c*s*f+h*i*n*f-t*c*n*f-o*i*d*f+t*a*d*f},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],a=e[4],n=e[5],l=e[6],h=e[7],c=e[8],d=e[9],u=e[10],p=e[11],m=e[12],_=e[13],f=e[14],g=e[15],v=i*n-s*a,b=i*l-r*a,y=i*h-o*a,M=s*l-r*n,w=s*h-o*n,P=r*h-o*l,x=c*_-d*m,E=c*f-u*m,A=c*g-p*m,C=d*f-u*_,R=d*g-p*_,S=u*g-p*f,L=1/(v*S-b*R+y*C+M*A-w*E+P*x);return t[0]=(n*S-l*R+h*C)*L,t[1]=(-s*S+r*R-o*C)*L,t[2]=(_*P-f*w+g*M)*L,t[3]=(-d*P+u*w-p*M)*L,t[4]=(-a*S+l*A-h*E)*L,t[5]=(i*S-r*A+o*E)*L,t[6]=(-m*P+f*y-g*b)*L,t[7]=(c*P-u*y+p*b)*L,t[8]=(a*R-n*A+h*x)*L,t[9]=(-i*R+s*A-o*x)*L,t[10]=(m*w-_*y+g*v)*L,t[11]=(-c*w+d*y-p*v)*L,t[12]=(-a*C+n*E-l*x)*L,t[13]=(i*C-s*E+r*x)*L,t[14]=(-m*M+_*b-f*v)*L,t[15]=(c*M-d*b+u*v)*L,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||math.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||math.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new FloatArrayType(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,math.translationMat4v(e,r))})(),translationMat4s:(e,t)=>math.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>math.translateMat4c(e[0],e[1],e[2],t),OLDtranslateMat4c(e,t,i,s){const r=s[12];s[0]+=r*e,s[4]+=r*t,s[8]+=r*i;const o=s[13];s[1]+=o*e,s[5]+=o*t,s[9]+=o*i;const a=s[14];s[2]+=a*e,s[6]+=a*t,s[10]+=a*i;const n=s[15];return s[3]+=n*e,s[7]+=n*t,s[11]+=n*i,s},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 a=s[11];s[8]+=a*e,s[9]+=a*t,s[10]+=a*i;const n=s[15];return s[12]+=n*e,s[13]+=n*t,s[14]+=n*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=math.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),a=1-o,n=s[0],l=s[1],h=s[2];let c,d,u,p,m,_;return c=n*l,d=l*h,u=h*n,p=n*r,m=l*r,_=h*r,(i=i||math.mat4())[0]=a*n*n+o,i[1]=a*c+_,i[2]=a*u-m,i[3]=0,i[4]=a*c-_,i[5]=a*l*l+o,i[6]=a*d+p,i[7]=0,i[8]=a*u+m,i[9]=a*d-p,i[10]=a*h*h+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>math.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=math.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=math.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new FloatArrayType(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,math.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=>math.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=math.mat4()){const s=e[0],r=e[1],o=e[2],a=e[3],n=s+s,l=r+r,h=o+o,c=s*n,d=s*l,u=s*h,p=r*l,m=r*h,_=o*h,f=a*n,g=a*l,v=a*h;return i[0]=1-(p+_),i[1]=d+v,i[2]=u-g,i[3]=0,i[4]=d-v,i[5]=1-(c+_),i[6]=m+f,i[7]=0,i[8]=u+g,i[9]=m-f,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=math.vec4()){const s=math.clamp,r=e[0],o=e[4],a=e[8],n=e[1],l=e[5],h=e[9],c=e[2],d=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-h,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(d,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[1]=Math.atan2(a,u),i[2]=Math.atan2(n,l)):(i[1]=Math.atan2(-c,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(d,-1,1)),Math.abs(d)<.99999?(i[1]=Math.atan2(-c,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(n,r))):"ZYX"===t?(i[1]=Math.asin(-s(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(d,u),i[2]=Math.atan2(n,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-h,l),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(a,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(d,l),i[1]=Math.atan2(a,r)):(i[0]=Math.atan2(-h,u),i[1]=0)),i},composeMat4:(e,t,i,s=math.mat4())=>(math.quaternionToRotationMat4(t,s),math.scaleMat4v(i,s),math.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new FloatArrayType(3),t=new FloatArrayType(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let a=math.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const n=math.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=math.lenVec3(e);math.determinantMat4(i)<0&&(a=-a),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const h=1/a,c=1/n,d=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=d,t[9]*=d,t[10]*=d,math.mat4ToQuaternion(t,r),o[0]=a,o[1]=n,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=math.mat4());const r=e[0],o=e[1],a=e[2],n=i[0],l=i[1],h=i[2],c=t[0],d=t[1],u=t[2];if(r===c&&o===d&&a===u)return math.identityMat4();let p,m,_,f,g,v,b,y,M,w;return p=r-c,m=o-d,_=a-u,f=l*(_*=w=1/Math.sqrt(p*p+m*m+_*_))-h*(m*=w),g=h*(p*=w)-n*_,v=n*m-l*p,(w=Math.sqrt(f*f+g*g+v*v))?(f*=w=1/w,g*=w,v*=w):(f=0,g=0,v=0),b=m*v-_*g,y=_*f-p*v,M=p*g-m*f,(w=Math.sqrt(b*b+y*y+M*M))?(b*=w=1/w,y*=w,M*=w):(b=0,y=0,M=0),s[0]=f,s[1]=b,s[2]=p,s[3]=0,s[4]=g,s[5]=y,s[6]=m,s[7]=0,s[8]=v,s[9]=M,s[10]=_,s[11]=0,s[12]=-(f*r+g*o+v*a),s[13]=-(b*r+y*o+M*a),s[14]=-(p*r+m*o+_*a),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,a,n,l)=>math.lookAtMat4v([e,t,i],[s,r,o],[a,n,l],[]),orthoMat4c(e,t,i,s,r,o,a){a||(a=math.mat4());const n=t-e,l=s-i,h=o-r;return a[0]=2/n,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2/l,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/h,a[11]=0,a[12]=-(e+t)/n,a[13]=-(s+i)/l,a[14]=-(o+r)/h,a[15]=1,a},frustumMat4v(e,t,i){i||(i=math.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];math.addVec4(r,s,tempMat1),math.subVec4(r,s,tempMat2);const o=2*s[2],a=tempMat2[0],n=tempMat2[1],l=tempMat2[2];return i[0]=o/a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/n,i[6]=0,i[7]=0,i[8]=tempMat1[0]/a,i[9]=tempMat1[1]/n,i[10]=-tempMat1[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,a){a||(a=math.mat4());const n=t-e,l=s-i,h=o-r;return a[0]=2*r/n,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2*r/l,a[6]=0,a[7]=0,a[8]=(t+e)/n,a[9]=(s+i)/l,a[10]=-(o+r)/h,a[11]=-1,a[12]=0,a[13]=0,a[14]=-o*r*2/h,a[15]=0,a},perspectiveMat4(e,t,i,s,r){const o=[],a=[];return o[2]=i,a[2]=s,a[1]=o[2]*Math.tan(e/2),o[1]=-a[1],a[0]=a[1]*t,o[0]=-a[0],math.frustumMat4v(o,a,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=math.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=math.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,a,n,l;const h=e[0],c=e[1],d=e[2],u=e[3],p=e[4],m=e[5],_=e[6],f=e[7],g=e[8],v=e[9],b=e[10],y=e[11],M=e[12],w=e[13],P=e[14],x=e[15];let E;for(let e=0;e{const e=new FloatArrayType(16),t=new FloatArrayType(16),i=new FloatArrayType(16);return function(s,r,o,a){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,a)}})(),lerpVec3(e,t,i,s,r,o){const a=o||math.vec3(),n=(e-t)/(i-t);return a[0]=s[0]+n*(r[0]-s[0]),a[1]=s[1]+n*(r[1]-s[1]),a[2]=s[2]+n*(r[2]-s[2]),a},lerpMat4(e,t,i,s,r,o){const a=o||math.mat4(),n=(e-t)/(i-t);return a[0]=s[0]+n*(r[0]-s[0]),a[1]=s[1]+n*(r[1]-s[1]),a[2]=s[2]+n*(r[2]-s[2]),a[3]=s[3]+n*(r[3]-s[3]),a[4]=s[4]+n*(r[4]-s[4]),a[5]=s[5]+n*(r[5]-s[5]),a[6]=s[6]+n*(r[6]-s[6]),a[7]=s[7]+n*(r[7]-s[7]),a[8]=s[8]+n*(r[8]-s[8]),a[9]=s[9]+n*(r[9]-s[9]),a[10]=s[10]+n*(r[10]-s[10]),a[11]=s[11]+n*(r[11]-s[11]),a[12]=s[12]+n*(r[12]-s[12]),a[13]=s[13]+n*(r[13]-s[13]),a[14]=s[14]+n*(r[14]-s[14]),a[15]=s[15]+n*(r[15]-s[15]),a},flatten(e){const t=[];let i,s,r,o,a;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=math.vec4()){const s=e[0]*math.DEGTORAD/2,r=e[1]*math.DEGTORAD/2,o=e[2]*math.DEGTORAD/2,a=Math.cos(s),n=Math.cos(r),l=Math.cos(o),h=Math.sin(s),c=Math.sin(r),d=Math.sin(o);return"XYZ"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l-h*c*d):"YXZ"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l+h*c*d):"ZXY"===t?(i[0]=h*n*l-a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l-h*c*d):"ZYX"===t?(i[0]=h*n*l-a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l+h*c*d):"YZX"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l-h*c*d):"XZY"===t&&(i[0]=h*n*l-a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l+h*c*d),i},mat4ToQuaternion(e,t=math.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],a=e[5],n=e[9],l=e[2],h=e[6],c=e[10];let d;const u=i+a+c;return u>0?(d=.5/Math.sqrt(u+1),t[3]=.25/d,t[0]=(h-n)*d,t[1]=(r-l)*d,t[2]=(o-s)*d):i>a&&i>c?(d=2*Math.sqrt(1+i-a-c),t[3]=(h-n)/d,t[0]=.25*d,t[1]=(s+o)/d,t[2]=(r+l)/d):a>c?(d=2*Math.sqrt(1+a-i-c),t[3]=(r-l)/d,t[0]=(s+o)/d,t[1]=.25*d,t[2]=(n+h)/d):(d=2*Math.sqrt(1+c-i-a),t[3]=(o-s)/d,t[0]=(r+l)/d,t[1]=(n+h)/d,t[2]=.25*d),t},vec3PairToQuaternion(e,t,i=math.vec4()){const s=Math.sqrt(math.dotVec3(e,e)*math.dotVec3(t,t));let r=s+math.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])):math.cross3Vec3(e,t,i),i[3]=r,math.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=math.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 FloatArrayType(16);return(t,i,s)=>(s=s||math.vec3(),math.quaternionToRotationMat4(t,e),math.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=math.vec4()){const s=e[0],r=e[1],o=e[2],a=e[3],n=t[0],l=t[1],h=t[2],c=t[3];return i[0]=a*n+s*c+r*h-o*l,i[1]=a*l+r*c+o*n-s*h,i[2]=a*h+o*c+s*l-r*n,i[3]=a*c-s*n-r*l-o*h,i},vec3ApplyQuaternion(e,t,i=math.vec3()){const s=t[0],r=t[1],o=t[2],a=e[0],n=e[1],l=e[2],h=e[3],c=h*s+n*o-l*r,d=h*r+l*s-a*o,u=h*o+a*r-n*s,p=-a*s-n*r-l*o;return i[0]=c*h+p*-a+d*-l-u*-n,i[1]=d*h+p*-n+u*-a-c*-l,i[2]=u*h+p*-l+c*-n-d*-a,i},quaternionToMat4(e,t){t=math.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],a=2*i,n=2*s,l=2*r,h=a*o,c=n*o,d=l*o,u=a*i,p=n*i,m=l*i,_=n*s,f=l*s,g=l*r;return t[0]=1-(_+g),t[1]=p+d,t[2]=m-c,t[4]=p-d,t[5]=1-(u+g),t[6]=f+h,t[8]=m+c,t[9]=f-h,t[10]=1-(u+_),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],a=i+i,n=s+s,l=r+r,h=i*a,c=i*n,d=i*l,u=s*n,p=s*l,m=r*l,_=o*a,f=o*n,g=o*l;return t[0]=1-(u+m),t[4]=c-g,t[8]=d+f,t[1]=c+g,t[5]=1-(h+m),t[9]=p-_,t[2]=d-f,t[6]=p+_,t[10]=1-(h+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=math.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)=>math.normalizeQuaternion(math.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=math.vec4()){const i=(e=math.normalizeQuaternion(e,tempVec4))[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 FloatArrayType(e||6),AABB2:e=>new FloatArrayType(e||4),OBB3:e=>new FloatArrayType(e||32),OBB2:e=>new FloatArrayType(e||16),Sphere3:(e,t,i,s)=>new FloatArrayType([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,a,n;const l=e[0],h=e[1],c=e[2],d=e[3],u=e[4],p=e[5],m=e[6],_=e[7],f=e[8],g=e[9],v=e[10],b=e[11],y=e[12],M=e[13],w=e[14],P=e[15];for(s=0;s{const e=new FloatArrayType(3),t=new FloatArrayType(3),i=new FloatArrayType(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],math.subVec3(t,e,i),Math.abs(math.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new FloatArrayType(3),t=new FloatArrayType(3),i=new FloatArrayType(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=math.subVec3(t,e,i),a=r[0]-s[0],n=s[3]-r[0],l=r[1]-s[1],h=s[4]-r[1],c=r[2]-s[2],d=s[5]-r[2];return o[0]+=a>n?a:n,o[1]+=l>h?l:h,o[2]+=c>d?c:d,Math.abs(math.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||math.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||math.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=math.AABB3())=>(e[0]=math.MAX_DOUBLE,e[1]=math.MAX_DOUBLE,e[2]=math.MAX_DOUBLE,e[3]=math.MIN_DOUBLE,e[4]=math.MIN_DOUBLE,e[5]=math.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=math.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 Float32Array(3);return(t,i,s)=>{i=i||math.AABB3();let r,o,a,n=math.MAX_DOUBLE,l=math.MAX_DOUBLE,h=math.MAX_DOUBLE,c=math.MIN_DOUBLE,d=math.MIN_DOUBLE,u=math.MIN_DOUBLE;for(let i=0,p=t.length;ic&&(c=r),o>d&&(d=o),a>u&&(u=a);return i[0]=n,i[1]=l,i[2]=h,i[3]=c,i[4]=d,i[5]=u,i}})(),OBB3ToAABB3(e,t=math.AABB3()){let i,s,r,o=math.MAX_DOUBLE,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=math.MIN_DOUBLE,h=math.MIN_DOUBLE,c=math.MIN_DOUBLE;for(let t=0,d=e.length;tl&&(l=i),s>h&&(h=s),r>c&&(c=r);return t[0]=o,t[1]=a,t[2]=n,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=math.AABB3()){let i,s,r,o=math.MAX_DOUBLE,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=math.MIN_DOUBLE,h=math.MIN_DOUBLE,c=math.MIN_DOUBLE;for(let t=0,d=e.length;tl&&(l=i),s>h&&(h=s),r>c&&(c=r);return t[0]=o,t[1]=a,t[2]=n,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new Float32Array(3);return(t,i)=>{i=i||math.vec4();let s,r=0,o=0,a=0;const n=t.length;for(s=0;sh&&(h=l);return i[3]=h,i}})(),positions3ToSphere3:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s)=>{s=s||math.vec4();let r,o=0,a=0,n=0;const l=i.length;let h=0;for(r=0;rh&&(h=d);return s[3]=h,s}})(),OBB3ToSphere3:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s)=>{s=s||math.vec4();let r,o=0,a=0,n=0;const l=i.length,h=l/4;for(r=0;rd&&(d=c);return s[3]=d,s}})(),getSphere3Center:(e,t=math.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],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](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]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=math.MAX_DOUBLE,e[1]=math.MAX_DOUBLE,e[2]=math.MIN_DOUBLE,e[3]=math.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]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]),s<=-t&&r<=-t?-1:s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=math.AABB2()){let i,s,r,o,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=math.MIN_DOUBLE,h=math.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>h&&(h=s);return t[0]=a,t[1]=n,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]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),a=.5*(s-t),n=r*r;return(2*t-2*i+o+a)*(r*n)+(-3*t+3*i-2*o-a)*n+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=math.vec3()){const r=t[0]-e[0],o=t[1]-e[1],a=t[2]-e[2],n=i[0]-e[0],l=i[1]-e[1],h=i[2]-e[2],c=o*h-a*l,d=a*n-r*h,u=r*l-o*n,p=Math.sqrt(c*c+d*d+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/p,s[1]=d/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3);return(o,a,n,l,h,c)=>{c=c||math.vec3();const d=math.subVec3(l,n,e),u=math.subVec3(h,n,t),p=math.cross3Vec3(a,u,i),m=math.dotVec3(d,p);if(m<1e-6)return null;const _=math.subVec3(o,n,s),f=math.dotVec3(_,p);if(f<0||f>m)return null;const g=math.cross3Vec3(_,d,r),v=math.dotVec3(a,g);if(v<0||f+v>m)return null;const b=math.dotVec3(u,g)/m;return c[0]=o[0]+b*a[0],c[1]=o[1]+b*a[1],c[2]=o[2]+b*a[2],c}})(),rayPlaneIntersect:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3);return(r,o,a,n,l,h)=>{h=h||math.vec3(),o=math.normalizeVec3(o,e);const c=math.subVec3(n,a,t),d=math.subVec3(l,a,i),u=math.cross3Vec3(c,d,s);math.normalizeVec3(u,u);const p=-math.dotVec3(a,u),m=-(math.dotVec3(r,u)+p)/math.dotVec3(o,u);return h[0]=r[0]+m*o[0],h[1]=r[1]+m*o[1],h[2]=r[2]+m*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3);return(s,r,o,a,n)=>{const l=math.subVec3(a,r,e),h=math.subVec3(o,r,t),c=math.subVec3(s,r,i),d=math.dotVec3(l,l),u=math.dotVec3(l,h),p=math.dotVec3(l,c),m=math.dotVec3(h,h),_=math.dotVec3(h,c),f=d*m-u*u;if(0===f)return null;const g=1/f,v=(m*p-u*_)*g,b=(d*_-u*p)*g;return n[0]=1-v-b,n[1]=b,n[2]=v,n}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=math.vec3()){const o=e[0],a=e[1],n=e[2];return r[0]=t[0]*o+i[0]*a+s[0]*n,r[1]=t[1]*o+i[1]*a+s[1]*n,r[2]=t[2]*o+i[2]*a+s[2]*n,r},mergeVertices(e,t,i,s){const r={},o=[],a=[],n=t?[]:null,l=i?[]:null,h=[];let c,d,u,p;let m,_,f=0;for(m=0,_=e.length;m<_;m+=3)c=e[m],d=e[m+1],u=e[m+2],void 0===r[p=`${Math.round(1e4*c)}_${Math.round(1e4*d)}_${Math.round(1e4*u)}`]&&(r[p]=a.length/3,a.push(c),a.push(d),a.push(u),t&&(n.push(t[m]),n.push(t[m+1]),n.push(t[m+2])),i&&(l.push(i[f]),l.push(i[f+1]))),o[m/3]=r[p],f+=2;for(m=0,_=s.length;m<_;m++)h[m]=o[s[m]];const g={positions:a,indices:h};return n&&(g.normals=n),l&&(g.uv=l),g},buildNormals:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3),o=new Float32Array(3);return(a,n,l)=>{let h,c;const d=new Array(a.length/3);let u,p,m,_,f,g,v;for(h=0,c=n.length;h{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3),o=new Float32Array(3),a=new Float32Array(3);return(n,l,h)=>{const c=new Float32Array(n.length);for(let d=0;d>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=3*(n=t[i]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,a=3*(n=t[i+1]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,a=3*(n=t[i+2]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],a={};let n,l,h,c,d;let u,p,m,_,f,g;for(p=0,_=e.length;p<_;p+=3){u=p/3,l=e[p],h=e[p+1],c=e[p+2],void 0===r[d=`${Math.round(1e4*l)}_${Math.round(1e4*h)}_${Math.round(1e4*c)}`]?r[d]=[u]:r[d].push(u);const i=math.normalizeVec3([t[p],t[p+1],t[p+2]]);o[u]=i,n=math.vec4([i[0],i[1],i[2],1]),a[u]=n}for(d in r)if(r.hasOwnProperty(d)){const e=r[d],t=e.length;for(p=0;p{const e=new Float32Array(16),t=new Float32Array(16),i=new Float32Array(4),s=new Float32Array(4),r=new Float32Array(4),o=new Float32Array(4);return(a,n,l,h,c,d)=>{const u=math.mulMat4(l,n,e),p=math.inverseMat4(u,t),m=a.width,_=a.height,f=(h[0]-m/2)/(m/2),g=-(h[1]-_/2)/(_/2);i[0]=f,i[1]=g,i[2]=-1,i[3]=1,math.transformVec4(p,i,s),math.mulVec4Scalar(s,1/s[3]),r[0]=f,r[1]=g,r[2]=1,r[3]=1,math.transformVec4(p,r,o),math.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],math.subVec3(o,s,d),math.normalizeVec3(d)}})(),canvasPosToLocalRay:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s,r,o,a,n,l)=>{math.canvasPosToWorldRay(i,s,r,a,e,t),math.worldRayToLocalRay(o,e,t,n,l)}})(),worldRayToLocalRay:(()=>{const e=new Float32Array(16),t=new Float32Array(4),i=new Float32Array(4);return(s,r,o,a,n)=>{const l=math.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,math.transformVec4(l,t,i),a[0]=i[0],a[1]=i[1],a[2]=i[2],math.transformVec3(l,o,n)}})(),buildKDTree:(()=>{const e=10,t=20,i=new Float32Array;return(s,r)=>{const o=s.length/3,a=new Array(o);for(let e=0;el[3]&&(l[3]=a[t]),a[t+1]l[4]&&(l[4]=a[t+1]),a[t+2]l[5]&&(l[5]=a[t+2])}}if(r.lengthe)return h.triangles=r,h.leaf=!0,h;i[0]=l[3]-l[0],i[1]=l[4]-l[1],i[2]=l[5]-l[2];let p=0;i[1]>i[p]&&(p=1),i[2]>i[p]&&(p=2),h.splitDim=p;const m=(l[p]+l[p+3])/2,_=new Array(r.length);let f=0;const g=new Array(r.length);let v=0;for(c=0,d=r.length;c=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=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const n=Math.sqrt(r*r+o*o+a*a);t[s+0]=r/n,t[s+1]=o/n,t[s+2]=a/n,s+=3}return t}};math.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const a=new Uint16Array(3),n=new Uint16Array(3),l=new Uint16Array(3),h=math.vec3(),c=math.vec3(),d=math.vec3(),u=math.vec3(),p=math.vec3(),m=math.vec3(),_=math.vec3();return function(f,g,v,b){!function(r,o){const a={};let n,l,h,c;const d=Math.pow(10,4);let u,p,m=0;for(u=0,p=r.length;uM)||(T=i[R.index1],k=i[R.index2],(!B&&T>65535||k>65535)&&(B=!0),y.push(T),y.push(k));return B?new Uint32Array(y):new Uint16Array(y)}}();const color=math.vec3();class ModelMemento{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){const s=t.rootMetaObject;if(!s)return;const r=s.getObjectIDsInSubtree();this.numObjects=0,this._mask=i?utils.apply(i,{}):null;const o=e.objects,a=!i||i.visible,n=!i||i.edges,l=!i||i.xrayed,h=!i||i.highlighted,c=!i||i.selected,d=!i||i.clippable,u=!i||i.pickable,p=!i||i.colorize,m=!i||i.opacity;for(var _=0,f=r.length;_{this._saveModelMemento(e)}),this.bimViewer._modelsExplorer.on("modelUnloaded",e=>{this._destroyModelMemento(e)}),this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{this.getEnabled()&&this.reset(),e.preventDefault()})}_saveModelMemento(e){const t=this.viewer.metaScene.metaModels[e];if(!t)return;const i=new ModelMemento;i.saveObjects(this.viewer.scene,t,{visible:!0,edges:!0,xrayed:!0,highlighted:!0,selected:!0,clippable:!0,pickable:!0,colorize:!0,opacity:!1}),this._modelMementos[e]=i}_restoreModelMemento(e){const t=this.viewer.metaScene.metaModels[e];t&&this._modelMementos[e].restoreObjects(this.viewer.scene,t)}_destroyModelMemento(e){delete this._modelMementos[e]}reset(){const e=this.viewer.scene.modelIds;for(var t=0,i=e.length;t{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{this.getEnabled()&&this.fit(),e.preventDefault()})}fit(){const e=this.viewer.scene,t=e.getAABB(e.visibleObjectIds);this.viewer.cameraFlight.flyTo({aabb:t}),this.viewer.cameraControl.pivotPos=math.getAABB3Center(t,tempVec3)}set fov(e){this.viewer.scene.cameraFlight.fitFOV=e}get fov(){return this.viewer.scene.cameraFlight.fitFOV}set duration(e){this.viewer.scene.cameraFlight.duration=e}get duration(){return this.viewer.scene.cameraFlight.duration}}class FirstPersonMode extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement,s=this.viewer.cameraControl,r=t.cameraControlNavModeMediator;s.navMode="orbit",s.followPointer=!0,this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),this.on("active",e=>{r.setFirstPersonModeActive(e),e?(s.followPointer=!0,s.pivoting=!1):s.pivoting=!0}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)})}}function closeEnough(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class HideTool extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?(i.classList.add("active"),this.viewer.cameraControl.doublePickFlyTo=!1):(i.classList.remove("active"),this.viewer.cameraControl.doublePickFlyTo=!0)}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._init()}_init(){var e=null;this._onHover=this.viewer.cameraControl.on("hover",t=>{this.getActive()&&this.getEnabled()&&(e&&(e.highlighted=!1,e=null),t.entity&&t.entity.isObject&&((e=t.entity).highlighted=!0))}),this._onHoverOff=this.viewer.cameraControl.on("hoverOff",t=>{this.getActive()&&this.getEnabled()&&e&&(e.highlighted=!1,e=null)});const t=math.vec2(),i=this.viewer.scene.input;this._onMousedown=i.on("mousedown",e=>{!i.mouseDownLeft||i.mouseDownRight||i.mouseDownMiddle||(t[0]=e[0],t[1]=e[1])}),this._onMouseup=i.on("mouseup",i=>{if(this.getActive()&&this.getEnabled()&&e){if(!closeEnough(t,i))return void(e=null);e.visible=!1,e.highlighted=!1,e=null}})}}function closeEnough$1(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class SelectionTool extends Controller{constructor(e,t){if(super(e),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{if(e)i.classList.add("active");else{i.classList.remove("active");const e=this.viewer.scene;e.setObjectsHighlighted(e.highlightedObjectIds,!1)}}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._initSectionMode()}_initSectionMode(){const e=this.viewer,t=e.cameraControl;var i=null;this._onHover=t.on("hover",e=>{this.getActive()&&this.getEnabled()&&(i&&(i.highlighted=!1,i=null),e.entity&&e.entity.isObject&&((i=e.entity).highlighted=!0))}),this._onHoverOff=t.on("hoverOff",e=>{this.getActive()&&this.getEnabled()&&i&&(i.highlighted=!1,i=null)});const s=math.vec2(),r=e.scene.input;this._onMousedown=r.on("mousedown",e=>{this.getActive()&&this.getEnabled()&&(!r.mouseDownLeft||r.mouseDownRight||r.mouseDownMiddle||(s[0]=e[0],s[1]=e[1]))}),this._onMouseup=r.on("mouseup",e=>{if(this.getActive()&&this.getEnabled()&&i){if(!closeEnough$1(s,e))return void(i=null);i.selected=!i.selected,i=null}})}}function closeEnough$2(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class QueryTool extends Controller{constructor(e,t){if(super(e),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._init()}_init(){const e=this.viewer,t=e.cameraControl;var i=null;this._onHover=t.on("hover",e=>{this.getActive()&&this.getEnabled()&&(i&&(i.highlighted=!1,i=null),e.entity&&e.entity.isObject&&((i=e.entity).highlighted=!0))}),this._onHoverOff=t.on("hoverOff",e=>{this.getActive()&&this.getEnabled()&&i&&(i.highlighted=!1,i=null)});const s=math.vec2(),r=e.scene.input;this._onMousedown=r.on("mousedown",e=>{this.getActive()&&this.getEnabled()&&(!r.mouseDownLeft||r.mouseDownRight||r.mouseDownMiddle||(s[0]=e[0],s[1]=e[1]))}),this._onMouseup=r.on("mouseup",t=>{if(this.getActive()&&this.getEnabled())if(i){if(!closeEnough$2(s,t))return void(i=null);const r=i.model;if(!r)return;const o=this.bimViewer.getLoadedProjectId();if(!o)return void this.error("Query tool: should be a project loaded - ignoring query-pick");const a=r.id,n=i.id,l=e.metaScene.metaObjects[n];if(!l)return;const h={projectId:o,modelId:a,objectId:n,objectName:l.name,objectType:l.type};this.fire("queryPicked",h),i=null}else this.fire("queryNotPicked",!1)})}}class Plugin{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._eventSubs={},t.addPlugin(this)}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=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 stats={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}},scenesRenderInfo={},sceneIDMap=new Map,taskQueue=new Queue,tickEvent={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},taskBudget=10,fpsSamples=[],numFPSSamples=30;let elapsedTime,lastTime=0,totalFPS=0;function Core(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(core.scenes[e.id])return void console.error(`[ERROR] Scene ${utils.inQuotes(e.id)} already exists`)}else e.id=sceneIDMap.addItem({});core.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;scenesRenderInfo[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},stats.components.scenes++,e.once("destroyed",()=>{sceneIDMap.removeItem(e.id),delete core.scenes[e.id],delete scenesRenderInfo[e.id],stats.components.scenes--})},this.clear=function(){let e;for(const t in core.scenes)core.scenes.hasOwnProperty(t)&&(e=core.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete core.scenes[e.id]))},this.scheduleTask=function(e,t){taskQueue.push(e),taskQueue.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;taskQueue.length>0&&(e<0||s0){var t=1e3/(elapsedTime=e-lastTime);totalFPS+=t,fpsSamples.push(t),fpsSamples.length>=30&&(totalFPS-=fpsSamples.shift()),stats.frame.fps=Math.round(totalFPS/fpsSamples.length)}runTasks(e),fireTickEvents(e),renderScenes(),lastTime=e,window.requestAnimationFrame(frame)};function runTasks(e){const t=core.runTasks(e+taskBudget),i=core.getNumTasks();stats.frame.tasksRun=t,stats.frame.tasksScheduled=i,stats.frame.tasksBudget=taskBudget}function fireTickEvents(e){for(var t in tickEvent.time=e,core.scenes)if(core.scenes.hasOwnProperty(t)){var i=core.scenes[t];tickEvent.sceneId=t,tickEvent.startTime=i.startTime,tickEvent.deltaTime=null!=tickEvent.prevTime?tickEvent.time-tickEvent.prevTime:0,i.fire("tick",tickEvent,!0)}tickEvent.prevTime=e}function renderScenes(){const e=core.scenes;let t,i,s,r,o;for(o in e)e.hasOwnProperty(o)&&(t=e[o],(i=scenesRenderInfo[o])||(i=scenesRenderInfo[o]={}),s=t.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==s&&(i.ticksPerOcclusionTest=s,i.renderCountdown=s),--t.occlusionTestCountdown<=0&&(t.doOcclusionTest(),t.occlusionTestCountdown=s),r=t.ticksPerRender,i.ticksPerRender!==r&&(i.ticksPerRender=r,i.renderCountdown=r),0==--i.renderCountdown&&(t.render(!1),i.renderCountdown=r))}window.requestAnimationFrame(frame);class Component{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 Component))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e,this._renderer=this.scene._renderer}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.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty()}glResort(){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(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Map),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);const r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;const o=this._events[e];return void 0!==o&&t.call(i||this,o),r}off(e){if(void 0===e||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+" "+utils.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,a=e.on,n=!1!==e.recompiles;if(i&&(utils.isNumeric(i)||utils.isString(i))){const e=i;if(!(i=this.scene.components[e]))return void this.error("Component not found: "+utils.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]))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+" "+utils.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+utils.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,d;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(c=0,d=(h=e.subs).length;c{delete this._ownedComponents[e.id]},this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():core.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(i=(t=this._attachments[e]).component,r=0,o=(s=t.subs).length;r0){for(R=f.length/3,g.push(0),g.push(1),g.push(0),v.push(.5),v.push(.5),f.push(0+l),f.push(d+h),f.push(0+c),M=0;M<=r;M++)w=Math.sin(M*p),P=Math.cos(M*p),S=.5*Math.sin(M*p)+.5,L=.5*Math.cos(M*p)+.5,g.push(t*w),g.push(1),g.push(t*P),v.push(S),v.push(L),f.push(t*w+l),f.push(d+h),f.push(t*P+c);for(M=0;M0){for(R=f.length/3,g.push(0),g.push(-1),g.push(0),v.push(.5),v.push(.5),f.push(0+l),f.push(0-d+h),f.push(0+c),M=0;M<=r;M++)w=Math.sin(M*p),P=Math.cos(M*p),S=.5*Math.sin(M*p)+.5,L=.5*Math.cos(M*p)+.5,g.push(i*w),g.push(-1),g.push(i*P),v.push(S),v.push(L),f.push(i*w+l),f.push(0-d+h),f.push(i*P+c);for(M=0;M360&&(o=360);const a=e.center;let n=a?a[0]:0,l=a?a[1]:0;const h=a?a[2]:0,c=[],d=[],u=[],p=[];let m,_,f,g,v,b,y,M,w,P,x,E;for(M=0;M<=r;M++)for(y=0;y<=s;y++)m=y/s*o,_=.785398+M/r*Math.PI*2,n=t*Math.cos(m),l=t*Math.sin(m),f=(t+i*Math.cos(_))*Math.cos(m),g=(t+i*Math.cos(_))*Math.sin(m),v=i*Math.sin(_),c.push(f+n),c.push(g+l),c.push(v+h),u.push(1-y/s),u.push(M/r),b=math.normalizeVec3(math.subVec3([f,g,v],[n,l,h],[]),[]),d.push(b[0]),d.push(b[1]),d.push(b[2]);for(M=1;M<=r;M++)for(y=1;y<=s;y++)w=(s+1)*M+y-1,P=(s+1)*(M-1)+y-1,x=(s+1)*(M-1)+y,E=(s+1)*M+y,p.push(w),p.push(P),p.push(x),p.push(x),p.push(E),p.push(w);return utils.apply(e,{positions:c,normals:d,uv:u,indices:p})}class Geometry extends Component{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),stats.memory.meshes++}destroy(){super.destroy(),stats.memory.meshes--}}class ArrayBuf{constructor(e,t,i,s,r,o,a,n,l){switch(this._gl=e,this.type=t,this.allocated=!1,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=!!a,this.stride=n||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)))}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)}}const WEBGL_INFO={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},canvas=document.createElement("canvas");if(canvas){const e=canvas.getContext("webgl",{antialias:!0})||canvas.getContext("experimental-webgl",{antialias:!0});WEBGL_INFO.WEBGL=!!e,WEBGL_INFO.WEBGL&&(WEBGL_INFO.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?WEBGL_INFO.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?WEBGL_INFO.FS_MAX_FLOAT_PRECISION="mediump":WEBGL_INFO.FS_MAX_FLOAT_PRECISION="lowp":WEBGL_INFO.FS_MAX_FLOAT_PRECISION="mediump",WEBGL_INFO.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),WEBGL_INFO.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),WEBGL_INFO.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),WEBGL_INFO.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),WEBGL_INFO.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),WEBGL_INFO.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),WEBGL_INFO.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),WEBGL_INFO.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),WEBGL_INFO.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),WEBGL_INFO.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach(function(e){WEBGL_INFO.SUPPORTED_EXTENSIONS[e]=!0}),WEBGL_INFO.depthTexturesSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.WEBGL_depth_texture)}var buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const a=new Uint16Array(3),n=new Uint16Array(3),l=new Uint16Array(3),h=math.vec3(),c=math.vec3(),d=math.vec3(),u=math.vec3(),p=math.vec3(),m=math.vec3(),_=math.vec3();return function(f,g,v,b){!function(r,o){const a={};let n,l,h,c;const d=Math.pow(10,4);let u,p,m=0;for(u=0,p=r.length;uM)||(T=i[R.index1],k=i[R.index2],(!B&&T>65535||k>65535)&&(B=!0),y.push(T),y.push(k));return B?new Uint32Array(y):new Uint16Array(y)}}();function getPositionsBounds(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;sa&&(r=i,a=o),(o=dot(e,n,s=octDecodeVec2(i=octEncodeVec3(e,n,"floor","ceil"))))>a&&(r=i,a=o),(o=dot(e,n,s=octDecodeVec2(i=octEncodeVec3(e,n,"ceil","ceil"))))>a&&(r=i,a=o),t[n]=r[0],t[n+1]=r[1];return t}function octEncodeVec3(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 octDecodeVec2(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 dot(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}function decompressUV(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]}function decompressUVs(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s=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}function decompressNormals(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const n=Math.sqrt(r*r+o*o+a*a);t[s+0]=r/n,t[s+1]=o/n,t[s+2]=a/n,s+=3}return t}const geometryCompressionUtils={getPositionsBounds:getPositionsBounds,createPositionsDecodeMatrix:createPositionsDecodeMatrix,compressPositions:compressPositions,decompressPositions:decompressPositions,decompressPosition:decompressPosition,decompressAABB:decompressAABB,getUVBounds:getUVBounds,compressUVs:compressUVs,decompressUVs:decompressUVs,decompressUV:decompressUV,compressNormals:compressNormals,decompressNormals:decompressNormals,decompressNormal:decompressNormal},memoryStats=stats.memory,bigIndicesSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,IndexArrayType=bigIndicesSupported?Uint32Array:Uint16Array,tempAABB=math.AABB3();class ReadableGeometry extends Geometry{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new RenderState({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=geometryCompressionUtils.getPositionsBounds(t.positions),s=geometryCompressionUtils.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=geometryCompressionUtils.getUVBounds(t.uv),s=geometryCompressionUtils.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);if(t.normals&&(this._state.compressGeometry?i.normals=geometryCompressionUtils.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices){if(!bigIndicesSupported&&t.indices.constructor===Uint32Array)return void this.error("This WebGL implementation does not support Uint32Array");i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new IndexArrayType(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),memoryStats.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),memoryStats.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),memoryStats.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),memoryStats.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),memoryStats.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),memoryStats.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=buildEdgeIndices(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),memoryStats.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=math.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),memoryStats.positions+=this._pickTrianglePositionsBuf.numItems,memoryStats.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),geometryCompressionUtils.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=geometryCompressionUtils.getPositionsBounds(e),s=geometryCompressionUtils.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),geometryCompressionUtils.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),geometryCompressionUtils.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=math.AABB3()),math.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=math.OBB3()),math.positions3ToAABB3(this._state.positions,tempAABB,this._state.positionsDecodeMatrix),math.AABB3ToOBB3(tempAABB,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),memoryStats.meshes--}}class Material extends Component{get type(){return"Material"}constructor(e,t={}){super(e,t),stats.memory.materials++}destroy(){super.destroy(),stats.memory.materials--}}const alphaModes={opaque:0,mask:1,blend:2},alphaModeNames=["opaque","mask","blend"];class PhongMaterial extends Material{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new RenderState({type:"PhongMaterial",ambient:math.vec3([1,1,1]),diffuse:math.vec3([1,1,1]),specular:math.vec3([1,1,1]),emissive:math.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=void 0!==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=alphaModes[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 alphaModeNames[this._state.alphaMode]}set alphaCutoff(e){null!==e&&void 0!==e||(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const PRESETS={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:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],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 EmphasisMaterial extends Material{get type(){return"EmphasisMaterial"}get presets(){return PRESETS}constructor(e,t={}){super(e,t),this._state=new RenderState({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!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)):(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)}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=void 0!==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=void 0!==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 preset(e){if(e=e||"default",this._preset===e)return;const t=PRESETS[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._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(PRESETS).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const angleAxis=new Float32Array(4),q1=new Float32Array(4),q2=new Float32Array(4),xAxis=new Float32Array([1,0,0]),yAxis=new Float32Array([0,1,0]),zAxis=new Float32Array([0,0,1]),veca=new Float32Array(3),vecb=new Float32Array(3),identityMat=math.identityMat4();class Node extends Component{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=math.vec3(),this._quaternion=math.identityQuaternion(),this._rotation=math.vec3(),this._position=math.vec3(),this._offset=math.vec3(),this._localMatrix=math.identityMat4(),this._worldMatrix=math.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.rtcCenter=t.rtcCenter,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;i0?"highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp":"mediump"}function buildVertexLambert(e){const t=e.scene._sectionPlanesState,i=e.scene._lightsState,s=e._geometry._state,r=e._state.billboard,o=e._state.stationary,a=t.sectionPlanes.length>0,n=!!s.compressGeometry;let l,h,c;const d=[];if(d.push("// Lambertian drawing vertex shader"),d.push("attribute vec3 position;"),d.push("uniform mat4 modelMatrix;"),d.push("uniform mat4 viewMatrix;"),d.push("uniform mat4 projMatrix;"),d.push("uniform vec4 colorize;"),d.push("uniform vec3 offset;"),n&&d.push("uniform mat4 positionsDecodeMatrix;"),a&&d.push("varying vec4 vWorldPosition;"),d.push("uniform vec4 lightAmbient;"),d.push("uniform vec4 materialColor;"),d.push("uniform vec3 materialEmissive;"),s.normalsBuf){for(d.push("attribute vec3 normal;"),d.push("uniform mat4 modelNormalMatrix;"),d.push("uniform mat4 viewNormalMatrix;"),l=0,h=i.lights.length;l= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),d.push(" }"),d.push(" return normalize(v);"),d.push("}"))}if(d.push("varying vec4 vColor;"),"points"===s.primitiveName&&d.push("uniform float pointSize;"),"spherical"!==r&&"cylindrical"!==r||(d.push("void billboard(inout mat4 mat) {"),d.push(" mat[0][0] = 1.0;"),d.push(" mat[0][1] = 0.0;"),d.push(" mat[0][2] = 0.0;"),"spherical"===r&&(d.push(" mat[1][0] = 0.0;"),d.push(" mat[1][1] = 1.0;"),d.push(" mat[1][2] = 0.0;")),d.push(" mat[2][0] = 0.0;"),d.push(" mat[2][1] = 0.0;"),d.push(" mat[2][2] =1.0;"),d.push("}")),d.push("void main(void) {"),d.push("vec4 localPosition = vec4(position, 1.0); "),d.push("vec4 worldPosition;"),n&&d.push("localPosition = positionsDecodeMatrix * localPosition;"),s.normalsBuf&&(n?d.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):d.push("vec4 localNormal = vec4(normal, 0.0); "),d.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),d.push("mat4 viewNormalMatrix2 = viewNormalMatrix;")),d.push("mat4 viewMatrix2 = viewMatrix;"),d.push("mat4 modelMatrix2 = modelMatrix;"),o&&d.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===r||"cylindrical"===r?(d.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),d.push("billboard(modelMatrix2);"),d.push("billboard(viewMatrix2);"),d.push("billboard(modelViewMatrix);"),s.normalsBuf&&(d.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),d.push("billboard(modelNormalMatrix2);"),d.push("billboard(viewNormalMatrix2);"),d.push("billboard(modelViewNormalMatrix);")),d.push("worldPosition = modelMatrix2 * localPosition;"),d.push("worldPosition.xyz = worldPosition.xyz + offset;"),d.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(d.push("worldPosition = modelMatrix2 * localPosition;"),d.push("worldPosition.xyz = worldPosition.xyz + offset;"),d.push("vec4 viewPosition = viewMatrix2 * worldPosition; ")),s.normalsBuf&&d.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);"),d.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),d.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),d.push("float lambertian = 1.0;"),s.normalsBuf)for(l=0,h=i.lights.length;l0,n=t.gammaOutput,l=[];if(l.push("// Lambertian drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),a)for(l.push("varying vec4 vWorldPosition;"),l.push("uniform bool clippable;"),r=0,o=i.sectionPlanes.length;r 0.0) { discard; }"),l.push("}")}return"points"===s.primitiveName&&(l.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),l.push("float r = dot(cxy, cxy);"),l.push("if (r > 1.0) {"),l.push(" discard;"),l.push("}")),n?l.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):l.push("gl_FragColor = vColor;"),l.push("}"),l}function buildVertexDraw(e){const t=e.scene,i=e._material,s=e._state,r=t._sectionPlanesState,o=e._geometry._state,a=t._lightsState;let n,l,h;const c=s.billboard,d=s.stationary,u=hasTextures(e),p=hasNormals(e),m=r.sectionPlanes.length>0,_=getReceivesShadow(e),f=!!o.compressGeometry,g=[];if(p&&i._normalMap&&g.push("#extension GL_OES_standard_derivatives : enable"),g.push("// Drawing vertex shader"),g.push("attribute vec3 position;"),f&&g.push("uniform mat4 positionsDecodeMatrix;"),g.push("uniform mat4 modelMatrix;"),g.push("uniform mat4 viewMatrix;"),g.push("uniform mat4 projMatrix;"),g.push("varying vec3 vViewPosition;"),g.push("uniform vec3 offset;"),m&&g.push("varying vec4 vWorldPosition;"),a.lightMaps.length>0&&g.push("varying vec3 vWorldNormal;"),p){for(g.push("attribute vec3 normal;"),g.push("uniform mat4 modelNormalMatrix;"),g.push("uniform mat4 viewNormalMatrix;"),g.push("varying vec3 vViewNormal;"),n=0,l=a.lights.length;n= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),g.push(" }"),g.push(" return normalize(v);"),g.push("}"))}if(u&&(g.push("attribute vec2 uv;"),g.push("varying vec2 vUV;"),f&&g.push("uniform mat3 uvDecodeMatrix;")),o.colors&&(g.push("attribute vec4 color;"),g.push("varying vec4 vColor;")),"points"===o.primitiveName&&g.push("uniform float pointSize;"),"spherical"!==c&&"cylindrical"!==c||(g.push("void billboard(inout mat4 mat) {"),g.push(" mat[0][0] = 1.0;"),g.push(" mat[0][1] = 0.0;"),g.push(" mat[0][2] = 0.0;"),"spherical"===c&&(g.push(" mat[1][0] = 0.0;"),g.push(" mat[1][1] = 1.0;"),g.push(" mat[1][2] = 0.0;")),g.push(" mat[2][0] = 0.0;"),g.push(" mat[2][1] = 0.0;"),g.push(" mat[2][2] =1.0;"),g.push("}")),_)for(g.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);"),n=0,l=a.lights.length;n0&&g.push("vWorldNormal = worldNormal;"),g.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),g.push("vec3 tmpVec3;"),g.push("float lightDist;"),n=0,l=a.lights.length;n0,h=hasNormals(e),c=r.uvBuf,d="PhongMaterial"===n.type,u="MetallicMaterial"===n.type,p="SpecularMaterial"===n.type,m=getReceivesShadow(e),_=(t.gammaInput,t.gammaOutput);let f,g;const v=[];if(v.push("// Drawing fragment shader"),h&&s._normalMap&&v.push("#extension GL_OES_standard_derivatives : enable"),v.push("precision "+getFragmentFloatPrecision(i)+" float;"),m&&(v.push("float unpackDepth (vec4 color) {"),v.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));"),v.push(" return dot(color, bitShift);"),v.push("}")),v.push("uniform float gammaFactor;"),v.push("vec4 linearToLinear( in vec4 value ) {"),v.push(" return value;"),v.push("}"),v.push("vec4 sRGBToLinear( in vec4 value ) {"),v.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 );"),v.push("}"),v.push("vec4 gammaToLinear( in vec4 value) {"),v.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),v.push("}"),_&&(v.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),v.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),v.push("}")),l){v.push("varying vec4 vWorldPosition;"),v.push("uniform bool clippable;");for(var b=0;b0&&(v.push("uniform samplerCube lightMap;"),v.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&v.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("uniform mat4 viewMatrix;"),v.push("#define PI 3.14159265359"),v.push("#define RECIPROCAL_PI 0.31830988618"),v.push("#define RECIPROCAL_PI2 0.15915494"),v.push("#define EPSILON 1e-6"),v.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),v.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),v.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),v.push("}"),v.push("struct IncidentLight {"),v.push(" vec3 color;"),v.push(" vec3 direction;"),v.push("};"),v.push("struct ReflectedLight {"),v.push(" vec3 diffuse;"),v.push(" vec3 specular;"),v.push("};"),v.push("struct Geometry {"),v.push(" vec3 position;"),v.push(" vec3 viewNormal;"),v.push(" vec3 worldNormal;"),v.push(" vec3 viewEyeDir;"),v.push("};"),v.push("struct Material {"),v.push(" vec3 diffuseColor;"),v.push(" float specularRoughness;"),v.push(" vec3 specularColor;"),v.push(" float shine;"),v.push("};"),d&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(v.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(v.push(" vec3 irradiance = "+TEXTURE_DECODE_FUNCS[a.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),v.push(" irradiance *= PI;"),v.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),v.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(v.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),v.push(" vec3 radiance = textureCube(reflectionMap, reflectVec).rgb * 0.2;"),v.push(" reflectedLight.specular += radiance;")),v.push("}")),v.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),v.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),v.push(" vec3 irradiance = dotNL * directLight.color * PI;"),v.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),v.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),v.push("}")),(u||p)&&(v.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),v.push(" float r = ggxRoughness + 0.0001;"),v.push(" return (2.0 / (r * r) - 2.0);"),v.push("}"),v.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),v.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),v.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),v.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),v.push("}"),a.reflectionMaps.length>0&&(v.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),v.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),v.push(" vec3 envMapColor = "+TEXTURE_DECODE_FUNCS[a.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),v.push(" return envMapColor;"),v.push("}")),v.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),v.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),v.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),v.push("}"),v.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),v.push(" float a2 = ( alpha * alpha );"),v.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),v.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),v.push(" return 1.0 / ( gl * gv );"),v.push("}"),v.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),v.push(" float a2 = ( alpha * alpha );"),v.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),v.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),v.push(" return 0.5 / max( gv + gl, EPSILON );"),v.push("}"),v.push("float D_GGX(const in float alpha, const in float dotNH) {"),v.push(" float a2 = ( alpha * alpha );"),v.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),v.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),v.push("}"),v.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),v.push(" float alpha = ( roughness * roughness );"),v.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),v.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),v.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),v.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),v.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),v.push(" vec3 F = F_Schlick( specularColor, dotLH );"),v.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),v.push(" float D = D_GGX( alpha, dotNH );"),v.push(" return F * (G * D);"),v.push("}"),v.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),v.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),v.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),v.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),v.push(" vec4 r = roughness * c0 + c1;"),v.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),v.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),v.push(" return specularColor * AB.x + AB.y;"),v.push("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(v.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(v.push(" vec3 irradiance = sRGBToLinear(textureCube(lightMap, geometry.worldNormal)).rgb;"),v.push(" irradiance *= PI;"),v.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),v.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(v.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),v.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),v.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),v.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),v.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),v.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),v.push("}")),v.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),v.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),v.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),v.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),v.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),v.push("}"))),v.push("varying vec3 vViewPosition;"),r.colors&&v.push("varying vec4 vColor;"),c&&(h&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&v.push("varying vec2 vUV;"),h&&(a.lightMaps.length>0&&v.push("varying vec3 vWorldNormal;"),v.push("varying vec3 vViewNormal;")),n.ambient&&v.push("uniform vec3 materialAmbient;"),n.baseColor&&v.push("uniform vec3 materialBaseColor;"),void 0!==n.alpha&&null!==n.alpha&&v.push("uniform vec4 materialAlphaModeCutoff;"),n.emissive&&v.push("uniform vec3 materialEmissive;"),n.diffuse&&v.push("uniform vec3 materialDiffuse;"),void 0!==n.glossiness&&null!==n.glossiness&&v.push("uniform float materialGlossiness;"),void 0!==n.shininess&&null!==n.shininess&&v.push("uniform float materialShininess;"),n.specular&&v.push("uniform vec3 materialSpecular;"),void 0!==n.metallic&&null!==n.metallic&&v.push("uniform float materialMetallic;"),void 0!==n.roughness&&null!==n.roughness&&v.push("uniform float materialRoughness;"),void 0!==n.specularF0&&null!==n.specularF0&&v.push("uniform float materialSpecularF0;"),c&&s._ambientMap&&(v.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&v.push("uniform mat4 ambientMapMatrix;")),c&&s._baseColorMap&&(v.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&v.push("uniform mat4 baseColorMapMatrix;")),c&&s._diffuseMap&&(v.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&v.push("uniform mat4 diffuseMapMatrix;")),c&&s._emissiveMap&&(v.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&v.push("uniform mat4 emissiveMapMatrix;")),h&&c&&s._metallicMap&&(v.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&v.push("uniform mat4 metallicMapMatrix;")),h&&c&&s._roughnessMap&&(v.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&v.push("uniform mat4 roughnessMapMatrix;")),h&&c&&s._metallicRoughnessMap&&(v.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&v.push("uniform mat4 metallicRoughnessMapMatrix;")),h&&s._normalMap&&(v.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&v.push("uniform mat4 normalMapMatrix;"),v.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),v.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),v.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),v.push(" vec2 st0 = dFdx( uv.st );"),v.push(" vec2 st1 = dFdy( uv.st );"),v.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),v.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),v.push(" vec3 N = normalize( surf_norm );"),v.push(" vec3 mapN = texture2D( normalMap, uv ).xyz * 2.0 - 1.0;"),v.push(" mat3 tsn = mat3( S, T, N );"),v.push(" return normalize( tsn * mapN );"),v.push("}")),c&&s._occlusionMap&&(v.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&v.push("uniform mat4 occlusionMapMatrix;")),c&&s._alphaMap&&(v.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&v.push("uniform mat4 alphaMapMatrix;")),h&&c&&s._specularMap&&(v.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&v.push("uniform mat4 specularMapMatrix;")),h&&c&&s._glossinessMap&&(v.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&v.push("uniform mat4 glossinessMapMatrix;")),h&&c&&s._specularGlossinessMap&&(v.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&v.push("uniform mat4 materialSpecularGlossinessMapMatrix;")),h&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(v.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),v.push(" float fr = abs(dot(eyeDir, normal));"),v.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),v.push(" return pow(finalFr, power);"),v.push("}"),s._diffuseFresnel&&(v.push("uniform float diffuseFresnelCenterBias;"),v.push("uniform float diffuseFresnelEdgeBias;"),v.push("uniform float diffuseFresnelPower;"),v.push("uniform vec3 diffuseFresnelCenterColor;"),v.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(v.push("uniform float specularFresnelCenterBias;"),v.push("uniform float specularFresnelEdgeBias;"),v.push("uniform float specularFresnelPower;"),v.push("uniform vec3 specularFresnelCenterColor;"),v.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(v.push("uniform float alphaFresnelCenterBias;"),v.push("uniform float alphaFresnelEdgeBias;"),v.push("uniform float alphaFresnelPower;"),v.push("uniform vec3 alphaFresnelCenterColor;"),v.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(v.push("uniform float materialSpecularF0FresnelCenterBias;"),v.push("uniform float materialSpecularF0FresnelEdgeBias;"),v.push("uniform float materialSpecularF0FresnelPower;"),v.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),v.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(v.push("uniform float emissiveFresnelCenterBias;"),v.push("uniform float emissiveFresnelEdgeBias;"),v.push("uniform float emissiveFresnelPower;"),v.push("uniform vec3 emissiveFresnelCenterColor;"),v.push("uniform vec3 emissiveFresnelEdgeColor;"))),v.push("uniform vec4 lightAmbient;"),h)for(b=0,f=a.lights.length;b 0.0) { discard; }"),v.push("}")}if("points"===r.primitiveName&&(v.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),v.push("float r = dot(cxy, cxy);"),v.push("if (r > 1.0) {"),v.push(" discard;"),v.push("}")),v.push("float occlusion = 1.0;"),n.ambient?v.push("vec3 ambientColor = materialAmbient;"):v.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);"),n.diffuse?v.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?v.push("vec3 diffuseColor = materialBaseColor;"):v.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);"),r.colors&&v.push("diffuseColor *= vColor.rgb;"),n.emissive?v.push("vec3 emissiveColor = materialEmissive;"):v.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);"),n.specular?v.push("vec3 specular = materialSpecular;"):v.push("vec3 specular = vec3(1.0, 1.0, 1.0);"),void 0!==n.alpha?v.push("float alpha = materialAlphaModeCutoff[0];"):v.push("float alpha = 1.0;"),r.colors&&v.push("alpha *= vColor.a;"),void 0!==n.glossiness?v.push("float glossiness = materialGlossiness;"):v.push("float glossiness = 1.0;"),void 0!==n.metallic?v.push("float metallic = materialMetallic;"):v.push("float metallic = 1.0;"),void 0!==n.roughness?v.push("float roughness = materialRoughness;"):v.push("float roughness = 1.0;"),void 0!==n.specularF0?v.push("float specularF0 = materialSpecularF0;"):v.push("float specularF0 = 1.0;"),c&&(h&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(v.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),v.push("vec2 textureCoord;")),c&&s._ambientMap&&(s._ambientMap._state.matrix?v.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 ambientTexel = texture2D(ambientMap, textureCoord).rgb;"),v.push("ambientTexel = "+TEXTURE_DECODE_FUNCS[s._ambientMap._state.encoding]+"(ambientTexel);"),v.push("ambientColor *= ambientTexel.rgb;")),c&&s._diffuseMap&&(s._diffuseMap._state.matrix?v.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 diffuseTexel = texture2D(diffuseMap, textureCoord);"),v.push("diffuseTexel = "+TEXTURE_DECODE_FUNCS[s._diffuseMap._state.encoding]+"(diffuseTexel);"),v.push("diffuseColor *= diffuseTexel.rgb;"),v.push("alpha *= diffuseTexel.a;")),c&&s._baseColorMap&&(s._baseColorMap._state.matrix?v.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 baseColorTexel = texture2D(baseColorMap, textureCoord);"),v.push("baseColorTexel = "+TEXTURE_DECODE_FUNCS[s._baseColorMap._state.encoding]+"(baseColorTexel);"),v.push("diffuseColor *= baseColorTexel.rgb;"),v.push("alpha *= baseColorTexel.a;")),c&&s._emissiveMap&&(s._emissiveMap._state.matrix?v.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 emissiveTexel = texture2D(emissiveMap, textureCoord);"),v.push("emissiveTexel = "+TEXTURE_DECODE_FUNCS[s._emissiveMap._state.encoding]+"(emissiveTexel);"),v.push("emissiveColor = emissiveTexel.rgb;")),c&&s._alphaMap&&(s._alphaMap._state.matrix?v.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("alpha *= texture2D(alphaMap, textureCoord).r;")),c&&s._occlusionMap&&(s._occlusionMap._state.matrix?v.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("occlusion *= texture2D(occlusionMap, textureCoord).r;")),h&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){for(c&&s._normalMap?(s._normalMap._state.matrix?v.push("textureCoord = (normalMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):v.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?v.push("textureCoord = (specularMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("specular *= texture2D(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?v.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("glossiness *= texture2D(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?v.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 specGlossRGB = texture2D(materialSpecularGlossinessMap, textureCoord).rgba;"),v.push("specular *= specGlossRGB.rgb;"),v.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?v.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("metallic *= texture2D(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?v.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("roughness *= texture2D(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?v.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec3 metalRoughRGB = texture2D(metallicRoughnessMap, textureCoord).rgb;"),v.push("metallic *= metalRoughRGB.b;"),v.push("roughness *= metalRoughRGB.g;")),v.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(v.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),v.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(v.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),v.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(v.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),v.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(v.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),v.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),v.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),v.push(" discard;"),v.push("}"),v.push("IncidentLight light;"),v.push("Material material;"),v.push("Geometry geometry;"),v.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),v.push("vec3 viewLightDir;"),d&&(v.push("material.diffuseColor = diffuseColor;"),v.push("material.specularColor = specular;"),v.push("material.shine = materialShininess;")),p&&(v.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),v.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),v.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),v.push("material.specularColor = specular;")),u&&(v.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),v.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),v.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),v.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),v.push("geometry.position = vViewPosition;"),a.lightMaps.length>0&&v.push("geometry.worldNormal = normalize(vWorldNormal);"),v.push("geometry.viewNormal = viewNormal;"),v.push("geometry.viewEyeDir = viewEyeDir;"),d&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||u)&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("computePBRLightMapping(geometry, material, reflectedLight);"),v.push("float shadow = 1.0;"),v.push("float shadowAcneRemover = 0.007;"),v.push("vec3 fragmentDepth;"),v.push("float texelSize = 1.0 / 1024.0;"),v.push("float amountInLight = 0.0;"),v.push("vec3 shadowCoord;"),v.push("vec4 rgbaDepth;"),v.push("float depth;"),b=0,f=a.lights.length;b0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function logErrors(e){console.error(e.join("\n"))}class Program{constructor(e,t){this.id=ids$1.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 Shader(e,e.VERTEX_SHADER,joinSansComments(this.source.vertex)),this._fragmentShader=new Shader(e,e.FRAGMENT_SHADER,joinSansComments(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void logErrors(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void logErrors(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void logErrors(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void logErrors(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 logErrors(this.errors);const a=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=r.sectionPlanes.length;h0&&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 EmphasisFillShaderSource{constructor(e){this.vertex=buildVertex(e),this.fragment=buildFragment(e)}}function buildVertex(e){const t=e.scene,i=t._lightsState,s=hasNormals$1(e),r=t._sectionPlanesState.sectionPlanes.length>0,o=!!e._geometry._state.compressGeometry,a=e._state.billboard,n=e._state.stationary,l=[];let h,c,d;if(l.push("// EmphasisFillShaderSource vertex shader"),l.push("attribute 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;"),o&&l.push("uniform mat4 positionsDecodeMatrix;"),r&&l.push("varying vec4 vWorldPosition;"),l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){for(l.push("attribute vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;"),h=0,c=i.lights.length;h= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}if(l.push("varying vec4 vColor;"),"spherical"!==a&&"cylindrical"!==a||(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===a&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),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;"),n&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===a||"cylindrical"===a?(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);"),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(h=0,c=i.lights.length;h0;let r,o;const a=[];if(a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),s)for(a.push("varying vec4 vWorldPosition;"),a.push("uniform bool clippable;"),r=0,o=t.sectionPlanes.length;r 0.0) { discard; }"),a.push("}")}return"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push(" discard;"),a.push("}")),a.push("gl_FragColor = vColor;"),i?a.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):a.push("gl_FragColor = vColor;"),a.push("}"),a}const ids$3=new Map({}),tempVec3a$3=math.vec3(),EmphasisFillRenderer=function(e,t){this.id=ids$3.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new EmphasisFillShaderSource(t),this._allocate(t)},xrayFillRenderers={};EmphasisFillRenderer.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=xrayFillRenderers[t];return i||(i=new EmphasisFillRenderer(t,e),xrayFillRenderers[t]=i,stats.memory.programs++),i._useCount++,i},EmphasisFillRenderer.prototype.put=function(){0==--this._useCount&&(ids$3.removeItem(this.id),this._program&&this._program.destroy(),delete xrayFillRenderers[this._hash],stats.memory.programs--)},EmphasisFillRenderer.prototype.webglContextRestored=function(){this._program=null},EmphasisFillRenderer.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,a=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,n=t._state,l=t._geometry._state,h=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(n.rtcCenterHash,h):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),n.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Edges drawing vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 edgeColor;"),o.push("uniform vec3 offset;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vColor;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===s&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===s||"cylindrical"===s?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; ")),o.push("vColor = edgeColor;"),t&&o.push("vWorldPosition = worldPosition;"),o.push(" gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$1(e){const t=e.scene._sectionPlanesState,i=e.scene.gammaOutput,s=t.sectionPlanes.length>0;let r,o;const a=[];if(a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),s)for(a.push("varying vec4 vWorldPosition;"),a.push("uniform bool clippable;"),r=0,o=t.sectionPlanes.length;r 0.0) { discard; }"),a.push("}")}return a.push("gl_FragColor = vColor;"),i?a.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):a.push("gl_FragColor = vColor;"),a.push("}"),a}const ids$4=new Map({}),tempVec3a$4=math.vec3(),EmphasisEdgesRenderer=function(e,t){this.id=ids$4.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new EmphasisEdgesShaderSource(t),this._allocate(t)},renderers={};EmphasisEdgesRenderer.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=renderers[t];return i||(i=new EmphasisEdgesRenderer(t,e),renderers[t]=i,stats.memory.programs++),i._useCount++,i},EmphasisEdgesRenderer.prototype.put=function(){0==--this._useCount&&(ids$4.removeItem(this.id),this._program&&this._program.destroy(),delete renderers[this._hash],stats.memory.programs--)},EmphasisEdgesRenderer.prototype.webglContextRestored=function(){this._program=null},EmphasisEdgesRenderer.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let a;const n=t._state,l=t._geometry,h=l._state,c=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(n.rtcCenterHash,c):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),n.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Mesh picking vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("varying vec4 vViewPosition;"),o.push("uniform vec3 offset;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===s&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"!==s&&"cylindrical"!==s||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);")),o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),t&&o.push(" vWorldPosition = worldPosition;"),o.push(" gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$2(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Mesh 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"),s.push("uniform vec4 pickColor;"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = pickColor; "),s.push("}"),s}const tempVec3a$5=math.vec3(),PickMeshRenderer=function(e,t){this._hash=e,this._shaderSource=new PickMeshShaderSource(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},renderers$1={};PickMeshRenderer.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=renderers$1[t];if(!i){if((i=new PickMeshRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$1[t]=i,stats.memory.programs++}return i._useCount++,i},PickMeshRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$1[this._hash],stats.memory.programs--)},PickMeshRenderer.prototype.webglContextRestored=function(){this._program=null},PickMeshRenderer.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,a=t._geometry._state,n=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,n?e.getRTCPickViewMatrix(r.rtcCenterHash,n):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,d=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,d/255,c/255,h/255),a.indicesBuf?(s.drawElements(a.primitive,a.indicesBuf.numItems,a.indicesBuf.itemType,0),e.drawElements++):a.positions&&s.drawArrays(s.TRIANGLES,0,a.positions.numItems)},PickMeshRenderer.prototype._allocate=function(e){const t=e.scene.canvas.gl;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e.scene._sectionPlanesState.sectionPlanes.length;t0,i=!!e._geometry._state.compressGeometry,s=(e._state.billboard,e._state.stationary,[]);return s.push("// Surface picking vertex shader"),s.push("attribute vec3 position;"),s.push("attribute vec4 color;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform vec3 offset;"),t&&(s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;")),s.push("varying vec4 vColor;"),i&&s.push("uniform mat4 positionsDecodeMatrix;"),s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;"),s.push(" vec4 worldPosition = modelMatrix * localPosition; "),s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vColor = color;"),s.push(" gl_Position = projMatrix * viewPosition;"),s.push("}"),s}function buildFragment$3(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Surface 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"),s.push("varying vec4 vColor;"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vColor;"),s.push("}"),s}const tempVec3a$6=math.vec3(),PickTriangleRenderer=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new PickTriangleShaderSource(t),this._allocate(t)},renderers$2={};PickTriangleRenderer.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=renderers$2[t];if(!i){if((i=new PickTriangleRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$2[t]=i,stats.memory.programs++}return i._useCount++,i},PickTriangleRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$2[this._hash],stats.memory.programs--)},PickTriangleRenderer.prototype.webglContextRestored=function(){this._program=null},PickTriangleRenderer.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,a=t._geometry,n=t._geometry._state,l=t.rtcCenter,h=o.backfaces,c=o.frontface,d=a._getPickTrianglePositions(),u=a._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.rtcCenterHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Mesh occlusion vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec3 offset;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===s&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"!==s&&"cylindrical"!==s||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);")),o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),t&&o.push(" vWorldPosition = worldPosition;"),o.push(" gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$4(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Mesh 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"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}const tempVec3a$7=math.vec3(),OcclusionRenderer=function(e,t){this._hash=e,this._shaderSource=new OcclusionShaderSource(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},renderers$3={};OcclusionRenderer.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=renderers$3[t];if(!i){if((i=new OcclusionRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$3[t]=i,stats.memory.programs++}return i._useCount++,i},OcclusionRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$3[this._hash],stats.memory.programs--)},OcclusionRenderer.prototype.webglContextRestored=function(){this._program=null},OcclusionRenderer.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,a=t._geometry._state,n=t.rtcCenter;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,n?e.getRTCViewMatrix(o.rtcCenterHash,n):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];return s.push("// Mesh shadow vertex shader"),s.push("attribute 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("varying 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;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}function buildFragment$5(e){const t=e.scene,i=(t.canvas.gl,t._sectionPlanesState),s=i.sectionPlanes.length>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("varying vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("gl_FragColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}const ShadowRenderer=function(e,t){this._hash=e,this._shaderSource=new ShadowShaderSource(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},renderers$4={};ShadowRenderer.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=renderers$4[i];if(!s){if((s=new ShadowRenderer(i,e)).errors)return console.log(s.errors.join("\n")),null;renderers$4[i]=s,stats.memory.programs++}return s._useCount++,s},ShadowRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$4[this._hash],stats.memory.programs--)},ShadowRenderer.prototype.webglContextRestored=function(){this._program=null},ShadowRenderer.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++)},ShadowRenderer.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Program(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;e0){let e,t,r,o,a;for(let n=0,l=this._uSectionPlanes.length;n0)for(let i=0;i-1){const V=L.geometry._state,O=L.scene,j=O.camera,U=O.canvas;if("triangles"===V.primitiveName){k.primitive="triangle";const O=B,G=V.indices,z=V.positions;let H,$,W,X;if(G){var I=G[O+0],F=G[O+1],N=G[O+2];o[0]=I,o[1]=F,o[2]=N,k.indices=o,H=3*I,$=3*F,W=3*N}else W=($=(H=3*O)+3)+3;if(i[0]=z[H+0],i[1]=z[H+1],i[2]=z[H+2],s[0]=z[$+0],s[1]=z[$+1],s[2]=z[$+2],r[0]=z[W+0],r[1]=z[W+1],r[2]=z[W+2],V.compressGeometry){const e=V.positionsDecodeMatrix;e&&(geometryCompressionUtils.decompressPosition(i,e,i),geometryCompressionUtils.decompressPosition(s,e,s),geometryCompressionUtils.decompressPosition(r,e,r))}k.canvasPos?(X=k.canvasPos,math.canvasPosToLocalRay(U.canvas,D,T,L.worldMatrix,X,e,t)):k.origin&&k.direction&&math.worldRayToLocalRay(L.worldMatrix,k.origin,k.direction,e,t),math.normalizeVec3(t),math.rayPlaneIntersect(e,t,i,s,r,a),k.localPos=a,k.position=a,f[0]=a[0],f[1]=a[1],f[2]=a[2],f[3]=1,math.transformVec4(L.worldMatrix,f,g),n[0]=g[0],n[1]=g[1],n[2]=g[2],k.worldPos=n,math.transformVec4(j.matrix,g,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],k.viewPos=l,math.cartesianToBarycentric(a,i,s,r,h),k.bary=h;const Y=V.normals;if(Y){if(V.compressGeometry){const e=3*I,t=3*F,i=3*N;geometryCompressionUtils.decompressNormal(Y.subarray(e,e+2),c),geometryCompressionUtils.decompressNormal(Y.subarray(t,t+2),d),geometryCompressionUtils.decompressNormal(Y.subarray(i,i+2),u)}else c[0]=Y[H],c[1]=Y[H+1],c[2]=Y[H+2],d[0]=Y[$],d[1]=Y[$+1],d[2]=Y[$+2],u[0]=Y[W],u[1]=Y[W+1],u[2]=Y[W+2];const e=math.addVec3(math.addVec3(math.mulVec3Scalar(c,h[0],b),math.mulVec3Scalar(d,h[1],y),M),math.mulVec3Scalar(u,h[2],w),P);k.worldNormal=math.normalizeVec3(math.transformVec3(L.worldNormalMatrix,e,x))}const q=V.uv;if(q){if(p[0]=q[2*I],p[1]=q[2*I+1],m[0]=q[2*F],m[1]=q[2*F+1],_[0]=q[2*N],_[1]=q[2*N+1],V.compressGeometry){const e=V.uvDecodeMatrix;e&&(geometryCompressionUtils.decompressUV(p,e,p),geometryCompressionUtils.decompressUV(m,e,m),geometryCompressionUtils.decompressUV(_,e,_))}k.uv=math.addVec3(math.addVec3(math.mulVec2Scalar(p,h[0],E),math.mulVec2Scalar(m,h[1],A),C),math.mulVec2Scalar(_,h[2],R),S)}}}}}();function buildSphereGeometry(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 a=e.heightSegments||18;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),(a=Math.floor(t*a))<18&&(a=18);let n=e.widthSegments||18;n<0&&(console.error("negative widthSegments not allowed - will invert"),n*=-1),(n=Math.floor(t*n))<18&&(n=18);const l=[],h=[],c=[],d=[];let u,p,m,_,f,g,v,b,y,M,w,P,x,E,A;for(u=0;u<=a;u++)for(m=u*Math.PI/a,_=Math.sin(m),f=Math.cos(m),p=0;p<=n;p++)g=2*p*Math.PI/n,v=Math.sin(g),y=(b=Math.cos(g))*_,M=f,w=v*_,P=1-p/n,x=u/a,h.push(y),h.push(M),h.push(w),c.push(P),c.push(x),l.push(i+o*y),l.push(s+o*M),l.push(r+o*w);for(u=0;u{this._setPos(this._sectionPlane.pos)}),this._onSectionPlaneDir=e.on("dir",()=>{this._setDir(this._sectionPlane.dir)}))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),worldToRTCPos(this._pos,this._rtcCenter,this._rtcPos),this._rootNode.rtcCenter=this._rtcCenter,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=math.vec3PairToQuaternion(zeroVec,e,quat)}setVisible(e=!0){if(this._visible!==e){var t;for(t in this._visible=e,this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].visible=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].visible=e)}}getVisible(){return this._visible}setCulled(e){var t;for(t in this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].culled=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].culled=e)}_createNodes(){const e=this._viewer.scene;this._rootNode=new Node(e,{position:[0,0,0],scale:[5,5,5]});const t=this._rootNode,i={arrowHead:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.01,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.01,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.01,radiusBottom:.01,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},s={pickable:new PhongMaterial(t,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new PhongMaterial(t,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new PhongMaterial(t,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new PhongMaterial(t,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new PhongMaterial(t,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new EmphasisMaterial(t,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,{primitive:"triangles",positions:[.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,.5,-0,.5,-.5,-0,-.5,-.5,-0,-.5,.5,-0],indices:[0,1,2,2,3,0]}),material:new PhongMaterial(t,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new EmphasisMaterial(t,{edges:!1,filled:!0,fillColor:[1,1,0],edgeColor:[0,0,0],fillAlpha:.1,backfaces:!0}),pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),!1),planeFrame:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildTorusGeometry({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new PhongMaterial(t,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new EmphasisMaterial(t,{edges:!1,edgeColor:[0,0,0],filled:!0,fillColor:[.8,.8,.8],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),!1),xCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.red,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,-.07,-.8,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(0*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),xCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,-.8,-.07,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),yCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),yCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(.07,0,-.8,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(.8,0,-.07,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.blue,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurveCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(.8,-.07,0,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4());return math.mulMat4(e,t,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(.05,-.8,0,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),center:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildSphereGeometry({radius:.05})),material:s.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),xAxis:t.addChild(new Mesh(t,{geometry:i.axis,material:s.red,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2}),!1),yShaft:t.addChild(new Mesh(t,{geometry:i.axis,material:s.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yShaftHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zShaft:t.addChild(new Mesh(t,{geometry:i.axis,material:s.blue,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),!1),zAxisHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1}),!1)},this._affordanceMeshes={planeFrame:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildTorusGeometry({center:[0,0,0],radius:2,tube:.01,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new PhongMaterial(t,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new EmphasisMaterial(t,{edges:!1,filled:!0,fillColor:[1,1,0],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,1],rotation:[0,0,45]}),!1),xHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.red,highlighted:!0,highlightMaterial:s.highlightRed,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.green,highlighted:!0,highlightMaterial:s.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.blue,highlighted:!0,highlightMaterial:s.highlightBlue,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.red,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.green,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.blue,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1)}}_bindEvents(){const e=this;var t=!1;const i=-1,s=0,r=1,o=2,a=3,n=4,l=5,h=this._rootNode;var c=null,d=null;const u=math.vec2(),p=math.vec3([1,0,0]),m=math.vec3([0,1,0]),_=math.vec3([0,0,1]),f=this._viewer.scene.canvas.canvas,g=this._viewer.camera,v=this._viewer.scene;{const e=math.vec3([0,0,0]);var b=-1;this._onCameraViewMatrix=v.camera.on("viewMatrix",()=>{}),this._onCameraProjMatrix=v.camera.on("projMatrix",()=>{}),this._onSceneTick=v.on("tick",()=>{var t=Math.abs(math.lenVec3(math.subVec3(v.camera.eye,h.position,e)));if(t!==b){const e=t/50*10;h.scale=[e,e,e],b=t}})}const y=function(){const e=new Float32Array(2);return function(t){if(t){for(var i=t.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-s,e[1]=t.pageY-r}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),M=function(){const t=math.mat4();return function(i,s){return math.quaternionToMat4(e._rootNode.quaternion,t),math.transformVec3(t,i,s),math.normalizeVec3(s),s}}();var w=function(){const e=math.vec3();return function(t){const i=Math.abs(t[0]);return i>Math.abs(t[1])&&i>Math.abs(t[2])?math.cross3Vec3(t,[0,1,0],e):math.cross3Vec3(t,[1,0,0],e),math.cross3Vec3(e,t,e),math.normalizeVec3(e),e}}();const P=function(){const t=math.vec3(),i=math.vec3(),s=math.vec4();return function(r,o,a){M(r,s);const n=w(s,o,a);E(o,n,t),E(a,n,i),math.subVec3(i,t);const l=math.dotVec3(i,s);e._pos[0]+=s[0]*l,e._pos[1]+=s[1]*l,e._pos[2]+=s[2]*l,e._rootNode.position=e._pos,e.sectionPlane&&(e.sectionPlane.pos=e._pos)}}();var x=function(){const t=math.vec4(),i=math.vec4(),s=math.vec4(),r=math.vec4();return function(o,a,n){if(M(o,r),!(E(a,r,t)&&E(n,r,i))){const e=w(r,a,n);E(a,e,t,1),E(n,e,i,1);var l=math.dotVec3(t,r);t[0]-=l*r[0],t[1]-=l*r[1],t[2]-=l*r[2],l=math.dotVec3(i,r),i[0]-=l*r[0],i[1]-=l*r[1],i[2]-=l*r[2]}math.normalizeVec3(t),math.normalizeVec3(i),l=math.dotVec3(t,i),l=math.clamp(l,-1,1);var h=Math.acos(l)*math.RADTODEG;math.cross3Vec3(t,i,s),math.dotVec3(s,r)<0&&(h=-h),e._rootNode.rotate(o,h),A()}}(),E=function(){const t=math.vec4([0,0,0,1]),i=math.mat4();return function(s,r,o,a){a=a||0,t[0]=s[0]/f.width*2-1,t[1]=-(s[1]/f.height*2-1),t[2]=0,t[3]=1,math.mulMat4(g.projMatrix,g.viewMatrix,i),math.inverseMat4(i),math.transformVec4(i,t,t),math.mulVec4Scalar(t,1/t[3]);var n=g.eye;math.subVec4(t,n,t);const l=e._sectionPlane.pos;var h=-math.dotVec3(l,r)-a,c=math.dotVec3(r,t);if(Math.abs(c)>.005){var d=-(math.dotVec3(r,n)+h)/c;return math.mulVec3Scalar(t,d,o),math.addVec3(o,n),math.subVec3(o,l,o),!0}return!1}}();const A=function(){const t=math.vec3(),i=math.mat4();return function(){e.sectionPlane&&(math.quaternionToMat4(h.quaternion,i),math.transformVec3(i,[0,0,1],t),e._sectionPlane.dir=t)}}();var C,R=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",e=>{if(!this._visible)return;if(R)return;var h;switch(t=!1,C&&(C.visible=!1),e.entity.id){case this._displayMeshes.xAxisArrowHandle.id:case this._displayMeshes.xAxisHandle.id:h=this._affordanceMeshes.xAxisArrow,c=s;break;case this._displayMeshes.yAxisArrowHandle.id:case this._displayMeshes.yShaftHandle.id:h=this._affordanceMeshes.yAxisArrow,c=r;break;case this._displayMeshes.zAxisArrowHandle.id:case this._displayMeshes.zAxisHandle.id:h=this._affordanceMeshes.zAxisArrow,c=o;break;case this._displayMeshes.xCurveHandle.id:h=this._affordanceMeshes.xHoop,c=a;break;case this._displayMeshes.yCurveHandle.id:h=this._affordanceMeshes.yHoop,c=n;break;case this._displayMeshes.zCurveHandle.id:h=this._affordanceMeshes.zHoop,c=l;break;default:return void(c=i)}h&&(h.visible=!0),C=h,t=!0}),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOut",e=>{this._visible&&(C&&(C.visible=!1),C=null,c=i)}),f.addEventListener("mousedown",this._canvasMouseDownListener=(e=>{if(e.preventDefault(),this._visible&&t)switch(this._viewer.cameraControl.pointerEnabled=!1,e.which){case 1:R=!0;var i=y(e);d=c,u[0]=i[0],u[1]=i[1]}})),f.addEventListener("mousemove",this._canvasMouseMoveListener=(e=>{if(!this._visible)return;if(!R)return;var t=y(e);const i=t[0],h=t[1];switch(d){case s:P(p,u,t);break;case r:P(m,u,t);break;case o:P(_,u,t);break;case a:x(p,u,t);break;case n:x(m,u,t);break;case l:x(_,u,t)}u[0]=i,u[1]=h})),f.addEventListener("mouseup",this._canvasMouseUpListener=(e=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,R&&(e.which,R=!1,t=!1))})),f.addEventListener("wheel",this._canvasWheelListener=(e=>{if(this._visible)Math.max(-1,Math.min(1,40*-e.deltaY))}))}_destroy(){this._unbindEvents(),this._destroyNodes()}_unbindEvents(){const e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=e.cameraControl;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix),r.off(this._onCameraControlHover),r.off(this._onCameraControlHoverLeave)}_destroyNodes(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}const defaultCSS=".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; } }";class Spinner extends Component{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='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){if(document.getElementById("xeokit-spinner-css"))return;const e=document.createElement("style");e.innerHTML=defaultCSS,e.id="xeokit-spinner-css",document.body.appendChild(e)}_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 WEBGL_CONTEXT_NAMES=["webgl","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Canvas extends Component{get type(){return"Canvas"}constructor(e,t={}){super(e,t),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.canvas.width=this.canvas.clientWidth,this.canvas.height=this.canvas.clientHeight,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=null,r=null,o=null,a=null,n=null,l=null,h=null;this._tick=this.scene.on("tick",function(){const e=i.canvas,t=window.innerWidth!==s||window.innerHeight!==r,c=e.clientWidth!==o||e.clientHeight!==a,d=e.offsetLeft!==n||e.offsetTop!==l,u=e.parentElement;if(t||c||d||u!==h){if(i._spinner._adjustPosition(),c||d){const t=e.clientWidth,s=e.clientHeight;if(c){let t,i=0;for(const e in core.scenes)core.scenes.hasOwnProperty(e)&&(i+=(t=core.scenes[e]).canvas.canvas.clientWidth*t.canvas.canvas.clientHeight);stats.memory.pixels=i,e.width=e.clientWidth,e.height=e.clientHeight}const r=i.boundary;r[0]=e.offsetLeft,r[1]=e.offsetTop,r[2]=t,r[3]=s,i.fire("boundary",r),o=t,a=s}t&&(s=window.innerWidth,r=window.innerHeight),d&&(n=e.offsetLeft,l=e.offsetTop),h=u}}),this._spinner=new Spinner(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId}),this.clearColorAmbient=t.clearColorAmbient}_createCanvas(){const e="xeokit-canvas-"+math.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+='',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-t){i._setVisible(!1);continue}const a=i.canvasPos,n=a[0],l=a[1];n+10<0||l+10<0||n-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=n,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{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.rtcCenter.join();let i=this._occlusionLayers[t];i||(i=new OcclusionLayer(this._scene,e.rtcCenter),this._occlusionLayers[i.rtcCenterHash]=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 void e.error("Marker has not been added to OcclusionTester");const i=e.rtcCenter.join();if(i!==t.rtcCenterHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.rtcCenterHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new OcclusionLayer(this._scene,e.rtcCenter),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.rtcCenter.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.rtcCenterHash],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;e0,t=[];return t.push("// OcclusionTester vertex shader"),t.push("attribute vec3 position;"),t.push("uniform mat4 modelMatrix;"),t.push("uniform mat4 viewMatrix;"),t.push("uniform mat4 projMatrix;"),e&&t.push("varying vec4 vWorldPosition;"),t.push("void main(void) {"),t.push("vec4 worldPosition = vec4(position, 1.0); "),t.push(" vec4 viewPosition = viewMatrix * worldPosition;"),e&&t.push(" vWorldPosition = worldPosition;"),t.push(" gl_Position = projMatrix * viewPosition;"),t.push(" gl_PointSize = "+POINT_SIZE+".0;"),t.push("}"),t}_buildFragmentShaderSource(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,i=[];if(i.push("// OcclusionTester fragment shader"),i.push("precision lowp float;"),t){i.push("varying vec4 vWorldPosition;");for(var s=0;s 0.0) { discard; }")}return i.push(" gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(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;e0){const e=s.sectionPlanes;for(let s=0;s= ( 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 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 \tgl_FragColor = packDepthToRGBA( 1.0- ambientOcclusion );\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 Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.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")}render(e){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",function(){e=!0});const t=math.mat4();return()=>(e&&math.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,a=t.drawingBufferHeight,n=s.camera.project._state,l=n.near,h=n.far,c=n.matrix,d=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;tempVec2[0]=o,tempVec2[1]=a,t.getExtension("OES_standard_derivatives"),t.viewport(0,0,o,a),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,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,d),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale),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,tempVec2),t.uniform1f(this._uRandomSeed,u),i.bindTexture(this._uDepthTexture,e,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)}destroy(){this._program.destroy()}}class SAOBlendRenderer{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._uColorTexture="uColorTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=null,this._aUV=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Program(e,{vertex:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n \n attribute vec3 aPosition;\n attribute vec2 aUV;\n \n varying vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\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 packDepthToRGBA( 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 varying vec2 vUV;\n \n uniform sampler2D uColorTexture;\n uniform sampler2D uOcclusionTexture;\n \n uniform float uOcclusionScale;\n uniform float uOcclusionCutoff;\n \n float unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, unPackFactors );\n }\n \n void main() {\n vec4 color = texture2D(uColorTexture, vUV);\n float ambient = smoothstep(uOcclusionCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, vUV))) * uOcclusionScale;\n gl_FragColor = vec4(color.rgb * (ambient), color.a);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Float32Array([1,1,0,1,0,0,1,0]),s=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._uColorTexture="uColorTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._uOcclusionScale=this._program.getLocation("uOcclusionScale"),this._uOcclusionCutoff=this._program.getLocation("uOcclusionCutoff")}render(e,t){if(this._programError)return;const i=this._scene.canvas.gl,s=this._program,r=i.drawingBufferWidth,o=i.drawingBufferHeight;i.viewport(0,0,r,o),i.clearColor(0,0,0,1),i.disable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT),s.bind(),s.bindTexture(this._uColorTexture,e,0),s.bindTexture(this._uOcclusionTexture,t,2),i.uniform1f(this._uOcclusionScale,1),i.uniform1f(this._uOcclusionCutoff,.01),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}class SAOBlurRenderer{constructor(e){this._scene=e,this._texelOffset=new Float32Array([0,0]),this._program=null,this._programError=!1,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=null,this._aUV=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Program(e,{vertex:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n \n attribute vec3 aPosition;\n attribute vec2 aUV;\n \n varying vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n \n varying vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture;\n \n uniform float uOcclusionScale;\n uniform float uOcclusionCutoff;\n \n uniform vec2 uTexelOffset;\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 float unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, unPackFactors );\n }\n \n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n\n vec4 packDepthToRGBA( 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 void main() {\n \n float centerOcclusion = unpackRGBAToDepth(texture2D(uOcclusionTexture, vUV));\n float centerDepth = unpackRGBAToDepth(texture2D(uDepthTexture, vUV));\n \n float gaussian[5];\n \n gaussian[0] = 0.153170;\n gaussian[1] = 0.144893;\n gaussian[2] = 0.122649;\n gaussian[3] = 0.092902;\n gaussian[4] = 0.062970;\n \n float totalWeight = gaussian[0];\n float sum = centerOcclusion * totalWeight;\n \n for (int r = 1; r <= 4; ++r) {\n \n vec2 uv = vUV + uTexelOffset * float(r) * 2.0;\n \n float occlusionSample = unpackRGBAToDepth(texture2D(uOcclusionTexture, uv));\n float depthSample = unpackRGBAToDepth(texture2D(uDepthTexture, uv));\n \n float weight = gaussian[r];\n weight *= max(0.0, 1.0 - 10.0 * abs(depthSample - centerDepth));\n \n sum += occlusionSample * weight;\n \n totalWeight += weight;\n }\n \n for (int r = 1; r <= 4; ++r) {\n \n vec2 uv = vUV + uTexelOffset * -float(r) * 2.0;\n \n float occlusionSample = unpackRGBAToDepth(texture2D(uOcclusionTexture, uv));\n float depthSample = unpackRGBAToDepth(texture2D(uDepthTexture, uv));\n \n float weight = gaussian[r];\n weight *= max(0.0, 1.0 - 10.0 * abs(depthSample - centerDepth));\n \n sum += occlusionSample * weight;\n \n totalWeight += weight;\n }\n \n float blurredOcclusion = (sum / (totalWeight + 0.0001));\n \n gl_FragColor = packDepthToRGBA(blurredOcclusion);\n \n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Float32Array([1,1,0,1,0,0,1,0]),s=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._uOcclusionScale=this._program.getLocation("uOcclusionScale"),this._uOcclusionCutoff=this._program.getLocation("uOcclusionCutoff"),this._uTexelOffset=this._program.getLocation("uTexelOffset")}render(e,t,i){if(this._programError)return;const s=this._scene.canvas.gl,r=this._program,o=s.drawingBufferWidth,a=s.drawingBufferHeight;0===i?(this._texelOffset[0]=1/o,this._texelOffset[1]=0):(this._texelOffset[0]=0,this._texelOffset[1]=1/a),s.viewport(0,0,o,a),s.clearColor(0,0,0,1),s.disable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT),r.bind(),r.bindTexture(this._uDepthTexture,e,1),r.bindTexture(this._uOcclusionTexture,t,2),s.uniform1f(this._uOcclusionScale,.9),s.uniform1f(this._uOcclusionCutoff,.3),s.uniform2fv(this._uTexelOffset,this._texelOffset),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()}}const Renderer=function(e,t){t=t||{};const i=new FrameContext(e),s=e.canvas.canvas,r=e.canvas.gl,o=!!t.transparent,a=t.alphaDepthMask,n=new Map({});let l={},h={},c=!0,d=!0,u=!0;const p=new RenderBuffer(s,r),m=new RenderBuffer(s,r),_=new RenderBuffer(s,r),f=new RenderBuffer(s,r),g=new RenderBuffer(s,r);let v=!1;const b=new SAOOcclusionRenderer(e),y=new SAOBlurRenderer(e),M=new SAOBlendRenderer(e);function w(){c&&(!function(){for(let e in l)if(l.hasOwnProperty(e)){const t=l[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}}(),c=!1,d=!0),d&&(!function(){for(let e in l)if(l.hasOwnProperty(e)){const t=l[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),d=!1,u=!0),u&&function(){for(let e in l)if(l.hasOwnProperty(e)){const t=l[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e0)for(i.withSAO=!0,A=0;A0)for(A=0;A0)for(A=0;A0)for(A=0;A0||N>0||T>0){if(r.enable(r.CULL_FACE),r.enable(r.BLEND),o?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):(r.blendEquation(r.FUNC_ADD),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA)),i.backfaces=!1,a||r.depthMask(!1),N>0)for(A=0;A0)for(A=0;A0)for(A=0;A0)for(A=0;A0||O>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),O>0)for(A=0;A0)for(A=0;A0||U>0||V>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),o?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),U>0)for(A=0;A0)for(A=0;A0||z>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),z>0)for(A=0;A0)for(A=0;A0||$>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),o?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),$>0)for(A=0;A<$;A++)w[A].drawSelectedEdgesTransparent(i);if(H>0)for(A=0;A{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),document.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:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownLeft=!1,this.mouseDownRight=!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:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}})),this.element.addEventListener("mousemove",this._mouseMoveListener=(e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("mousemove",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault())})),this.element.addEventListener("wheel",this._mouseWheelListener=((e,t)=>{if(!this.enabled)return;const i=Math.max(-1,Math.min(1,40*-e.deltaY));this.fire("mousewheel",i,!0)}),{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)})}{const e={"landscape-primary":90,"landscape-secondary":-90,"portrait-secondary":180,"portrait-primary":0};let t,i;const s=math.vec3(),r=math.vec3(),o={orientation:null,orientationAngle:0},a={orientationAngle:0,acceleration:null,accelerationIncludingGravity:r,rotationRate:math.vec3(),interval:0},n={alpha:0,beta:0,gamma:0,absolute:!1};window.OrientationChangeEvent&&window.addEventListener("orientationchange",this._orientationchangedListener=(()=>{t=window.screen.orientation||window.screen.mozOrientation||window.msOrientation||null,i=t&&e[t]||0,o.orientation=t,o.orientationAngle=i,this.fire("orientationchange",o)}),!1),window.DeviceMotionEvent&&window.addEventListener("devicemotion",this._deviceMotionListener=(e=>{a.interval=e.interval,a.orientationAngle=i;const t=e.acceleration;t?(s[0]=t.x,s[1]=t.y,s[2]=t.z,a.acceleration=s):a.acceleration=null;const o=e.accelerationIncludingGravity;o?(r[0]=o.x,r[1]=o.y,r[2]=o.z,a.accelerationIncludingGravity=r):a.accelerationIncludingGravity=null,a.rotationRate=e.rotationRate,this.fire("devicemotion",a)}),!1),window.DeviceOrientationEvent&&window.addEventListener("deviceorientation",this._deviceOrientListener=(e=>{n.gamma=e.gamma,n.beta=e.beta,n.alpha=e.alpha,n.absolute=e.absolute,this.fire("deviceorientation",n)}),!1)}this._eventsBound=!0}}_unbindEvents(){this._eventsBound&&(document.removeEventListener("keydown",this._keyDownListener),document.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}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 Viewport extends Component{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new RenderState({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 Perspective extends Component{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:2e3}),this._dirty=!1,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.viewport.boundary,t=e[2]/e[3];let i=this._fov;const s=this._fovAxis;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),math.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set fov(e){this._fov=void 0!==e&&null!==e?e:60,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=void 0!==e&&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=void 0!==e&&null!==e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}destroy(){super.destroy(),this._state.destroy(),super.destroy(),this.scene.canvas.off(this._canvasResized)}}class Ortho extends Component{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:2e3}),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.viewport.boundary,s=i[2],r=i[3],o=s/r;let a,n,l,h;s>r?(a=-t,n=t,l=t/o,h=-t/o):(a=-t*o,n=t*o,l=t,h=-t),math.orthoMat4c(a,n,h,l,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){void 0!==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=void 0!==e&&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=void 0!==e&&null!==e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class Frustum extends Component{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,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(){math.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=void 0!==e&&null!==e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=void 0!==e&&null!==e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=void 0!==e&&null!==e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=void 0!==e&&null!==e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=void 0!==e&&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=void 0!==e&&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}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class CustomProjection extends Component{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4()}),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.glRedraw(),this.fire("far",this._state.matrix)}get matrix(){return this._state.matrix}destroy(){super.destroy(),this._state.destroy()}}const tempVec3$1=math.vec3(),tempVec3b=math.vec3(),tempVec3c=math.vec3(),tempVec3d=math.vec3(),tempVec3e=math.vec3(),tempVec3f=math.vec3(),tempMat=math.mat4(),tempMatb=math.mat4(),eyeLookVec=math.vec3(),eyeLookVecNorm=math.vec3(),eyeLookOffset=math.vec3(),offsetEye=math.vec3();class Camera extends Component{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new RenderState({deviceMatrix:math.mat4(),hasDeviceMatrix:!1,matrix:math.mat4(),normalMatrix:math.mat4()}),this._perspective=new Perspective(this),this._ortho=new Ortho(this),this._frustum=new Frustum(this),this._customProjection=new CustomProjection(this),this._project=this._perspective,this._eye=math.vec3([0,0,10]),this._look=math.vec3([0,0,0]),this._up=math.vec3([0,1,0]),this._worldUp=math.vec3([0,1,0]),this._worldRight=math.vec3([1,0,0]),this._worldForward=math.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?(math.subVec3(this._eye,this._look,eyeLookVec),math.normalizeVec3(eyeLookVec,eyeLookVecNorm),math.mulVec3Scalar(eyeLookVecNorm,1e3,eyeLookOffset),math.addVec3(this._look,eyeLookOffset,offsetEye),t=offsetEye):t=this._eye,e.hasDeviceMatrix?(math.lookAtMat4v(t,this._look,this._up,tempMatb),math.mulMat4(e.deviceMatrix,tempMatb,e.matrix)):math.lookAtMat4v(t,this._look,this._up,e.matrix),math.inverseMat4(this._state.matrix,this._state.normalMatrix),math.transposeMat4(this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=math.subVec3(this._eye,this._look,tempVec3$1);math.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tempMat),t=math.transformPoint3(tempMat,t,tempVec3b),this.eye=math.addVec3(this._look,t,tempVec3c),this.up=math.transformPoint3(tempMat,this._up,tempVec3d)}orbitPitch(e){if(this._constrainPitch&&(e=math.dotVec3(this._up,this._worldUp)/math.DEGTORAD)<1)return;let t=math.subVec3(this._eye,this._look,tempVec3$1);const i=math.cross3Vec3(math.normalizeVec3(t,tempVec3b),math.normalizeVec3(this._up,tempVec3c));math.rotationMat4v(.0174532925*e,i,tempMat),t=math.transformPoint3(tempMat,t,tempVec3d),this.up=math.transformPoint3(tempMat,this._up,tempVec3e),this.eye=math.addVec3(t,this._look,tempVec3f)}yaw(e){let t=math.subVec3(this._look,this._eye,tempVec3$1);math.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tempMat),t=math.transformPoint3(tempMat,t,tempVec3b),this.look=math.addVec3(t,this._eye,tempVec3c),this._gimbalLock&&(this.up=math.transformPoint3(tempMat,this._up,tempVec3d))}pitch(e){if(this._constrainPitch&&(e=math.dotVec3(this._up,this._worldUp)/math.DEGTORAD)<1)return;let t=math.subVec3(this._look,this._eye,tempVec3$1);const i=math.cross3Vec3(math.normalizeVec3(t,tempVec3b),math.normalizeVec3(this._up,tempVec3c));math.rotationMat4v(.0174532925*e,i,tempMat),this.up=math.transformPoint3(tempMat,this._up,tempVec3f),t=math.transformPoint3(tempMat,t,tempVec3d),this.look=math.addVec3(t,this._eye,tempVec3e)}pan(e){const t=math.subVec3(this._eye,this._look,tempVec3$1),i=[0,0,0];let s;if(0!==e[0]){const r=math.cross3Vec3(math.normalizeVec3(t,[]),math.normalizeVec3(this._up,tempVec3b));s=math.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=math.mulVec3Scalar(math.normalizeVec3(this._up,tempVec3c),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=math.mulVec3Scalar(math.normalizeVec3(t,tempVec3d),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=math.addVec3(this._eye,i,tempVec3e),this.look=math.addVec3(this._look,i,tempVec3f)}zoom(e){const t=math.subVec3(this._eye,this._look,tempVec3$1),i=Math.abs(math.lenVec3(t,tempVec3b)),s=Math.abs(i+e);if(s<.5)return;const r=math.normalizeVec3(t,tempVec3c);this.eye=math.addVec3(this._look,math.mulVec3Scalar(r,s),tempVec3d)}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=math.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 math.lenVec3(math.subVec3(this._look,this._eye,tempVec3$1))}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 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}destroy(){super.destroy(),this._state.destroy()}}class Light extends Component{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class DirLight extends Light{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 RenderState({type:"dir",dir:math.vec3([1,1,1]),color:math.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=math.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];math.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=math.identityMat4()),math.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new RenderBuffer(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class AmbientLight extends Light{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:math.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()}}function buildBoxGeometry(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,a=r?r[1]:0,n=r?r[2]:0,l=-t+o,h=-i+a,c=-s+n,d=t+o,u=i+a,p=s+n;return utils.apply(e,{positions:[d,u,p,l,u,p,l,h,p,d,h,p,d,u,p,d,h,p,d,h,c,d,u,c,d,u,p,d,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,d,h,c,d,h,p,l,h,p,d,h,c,l,h,c,l,u,c,d,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]})}const PRESETS$1={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 EdgeMaterial extends Material{get type(){return"EdgeMaterial"}get presets(){return PRESETS$1}constructor(e,t={}){super(e,t),this._state=new RenderState({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=void 0!==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=PRESETS$1[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(PRESETS$1).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const unitsInfo={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 Metrics extends Component{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=math.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return unitsInfo}set units(e){e||(e="meters"),unitsInfo[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=math.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=math.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 SAO extends Component{constructor(e,t={}){super(e,t),this._supported=WEBGL_INFO.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.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.scene._needRecompile=!0,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){void 0!==e&&null!==e||(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){void 0!==e&&null!==e||(e=.2),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){void 0!==e&&null!==e||(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){void 0!==e&&null!==e||(e=500),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){void 0!==e&&null!==e||(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){void 0!==e&&null!==e||(e=.2),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){void 0!==e&&null!==e||(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}function getEntityIDMap(e,t){const i={};let s,r;for(let o=0,a=t.length;o{this.glRedraw()}),this.canvas.on("webglContextFailed",()=>{alert("xeokit failed to find WebGL!")}),this._renderer=new Renderer(this,{transparent:i,alphaDepthMask:s}),this._sectionPlanesState=new function(){this.sectionPlanes=[];let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";let i;const s=[];for(let e=0,r=t.length;e0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join("")},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{this._renderer.imageDirty()})}_initDefaults(){let e;e=this.geometry,e=this.material,e=this.xrayMaterial,e=this.edgeMaterial,e=this.selectedMaterial,e=this.highlightMaterial}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+utils.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=math.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],utils.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])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!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}_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){delete this.models[e.id],this._modelIds=null}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(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}_objectSelectedUpdated(e){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(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}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&core.runTasks();const t={sceneId:null,pass:0};this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),h=!0}h||(t=-100,i=-100,s=-100,r=100,o=100,a=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=getEntityIDMap(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=getEntityIDMap(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity.fire&&t.entity.fire("picked",t),t):void 0}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{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>a&&(a=l[4]),l[5]>n&&(n=l[5]),t=!0}}),t){const e=math.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=a,e[5]=n,e}return this.aabb}setObjectsVisible(e,t){return this._withEntities(e,this.objects,e=>{const i=e.visible!==t;return e.visible=t,i})}setObjectsCollidable(e,t){return this._withEntities(e,this.objects,e=>{const i=e.collidable!==t;return e.collidable=t,i})}setObjectsCulled(e,t){return this._withEntities(e,this.objects,e=>{const i=e.culled!==t;return e.culled=t,i})}setObjectsSelected(e,t){return this._withEntities(e,this.objects,e=>{const i=e.selected!==t;return e.selected=t,i})}setObjectsHighlighted(e,t){return this._withEntities(e,this.objects,e=>{const i=e.highlighted!==t;return e.highlighted=t,i})}setObjectsXRayed(e,t){return this._withEntities(e,this.objects,e=>{const i=e.xrayed!==t;return e.xrayed=t,i})}setObjectsEdges(e,t){return this._withEntities(e,this.objects,e=>{const i=e.edges!==t;return e.edges=t,i})}setObjectsColorized(e,t){return this._withEntities(e,this.objects,e=>{e.colorize=t})}setObjectsOpacity(e,t){return this._withEntities(e,this.objects,e=>{const i=e.opacity!==t;return e.opacity=t,i})}setObjectsPickable(e,t){return this._withEntities(e,this.objects,e=>{const i=e.pickable!==t;return e.pickable=t,i})}setObjectsOffset(e,t){this._withEntities(e,this.objects,e=>{e.offset=t})}_withEntities(e,t,i){utils.isString(e)&&(e=[e]);let s=!1;for(let r=0,o=e.length;r{const o=this._sectionPlane.scene.center,a=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];math.subVec3(o,this._sectionPlane.pos,e);const n=-math.dotVec3(a,e);math.normalizeVec3(a),math.mulVec3Scalar(a,n,t);const l=math.vec3PairToQuaternion(i,this._sectionPlane.dir,s);r[0]=.1*t[0],r[1]=.1*t[1],r[2]=.1*t[2],this._mesh.quaternion=l,this._mesh.position=r};this._onSectionPlanePos=this._sectionPlane.on("pos",o),this._onSectionPlaneDir=this._sectionPlane.on("dir",o)}this._highlighted=!1,this._selected=!1}setHighlighted(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}getHighlighted(){return this._highlighted}setSelected(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}getSelected(){return this._selected}destroy(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}class Overview{constructor(e,t){if(!(t.onHoverEnterPlane&&t.onHoverLeavePlane&&t.onClickedNothing&&t.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=e,this._viewer=e.viewer,this._onHoverEnterPlane=t.onHoverEnterPlane,this._onHoverLeavePlane=t.onHoverLeavePlane,this._onClickedNothing=t.onClickedNothing,this._onClickedPlane=t.onClickedPlane,this._visible=!0,this._planes={},this._canvas=t.overviewCanvas,this._scene=new Scene({canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new DirLight(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new DirLight(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new DirLight(this._scene,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._scene.camera,this._scene.camera.perspective.fov=70,this._zUp=!1;{const e=this._scene.camera,t=math.rotationMat4c(-90*math.DEGTORAD,1,0,0),i=math.vec3(),s=math.vec3(),r=math.vec3();this._synchCamera=(()=>{const o=this._viewer.camera.eye,a=this._viewer.camera.look,n=this._viewer.camera.up;math.mulVec3Scalar(math.normalizeVec3(math.subVec3(o,a,i)),7),this._zUp?(math.transformVec3(t,i,s),math.transformVec3(t,n,r),e.look=[0,0,0],e.eye=math.transformVec3(t,i,s),e.up=math.transformPoint3(t,n,r)):(e.look=[0,0,0],e.eye=i,e.up=n)})}this._onViewerCameraMatrix=this._viewer.camera.on("matrix",this._synchCamera),this._onViewerCameraWorldAxis=this._viewer.camera.on("worldAxis",this._synchCamera),this._onViewerCameraFOV=this._viewer.camera.perspective.on("fov",e=>{this._scene.camera.perspective.fov=e}),this._onViewerCameraProjection=this._viewer.camera.on("projection",e=>{this._scene.camera.projection=e});var i=null;this._onInputMouseMove=this._scene.input.on("mousemove",e=>{const t=this._scene.pick({canvasPos:e});if(t){if(!i||t.entity.id!==i.id){if(i){this._planes[i.id]&&this._onHoverLeavePlane(i.id)}i=t.entity,this._planes[i.id]&&this._onHoverEnterPlane(i.id)}}else i&&(this._onHoverLeavePlane(i.id),i=null)}),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=(()=>{if(i){this._planes[i.id]&&this._onClickedPlane(i.id)}else this._onClickedNothing()})),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=(()=>{i&&(this._onHoverLeavePlane(i.id),i=null)})),this.setVisible(t.overviewVisible)}addSectionPlane(e){this._planes[e.id]=new Plane(this,this._scene,e)}setPlaneHighlighted(e,t){const i=this._planes[e];i&&i.setHighlighted(t)}setPlaneSelected(e,t){const i=this._planes[e];i&&i.setSelected(t)}removeSectionPlane(e){const t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}setVisible(e=!0){this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}getVisible(){return this._visible}destroy(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),this._viewer.camera.off(this._onViewerCameraProjection),this._scene.input.off(this._onInputMouseMove),this._scene.canvas.canvas.removeEventListener("mouseup",this._onCanvasMouseUp),this._scene.canvas.canvas.removeEventListener("mouseout",this._onCanvasMouseOut),this._scene.destroy()}}const tempAABB$1=math.AABB3(),tempVec3$2=math.vec3();class SectionPlanesPlugin extends Plugin{constructor(e,t={}){if(super("SectionPlanes",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new Overview(this,{overviewCanvas:e,visible:t.overviewVisible,onHoverEnterPlane:e=>{this._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:e=>{this._overview.setPlaneHighlighted(e,!1)},onClickedPlane:e=>{if(this.getShownControl()===e)return void this.hideControl();this.showControl(e);const t=this.sectionPlanes[e].pos;tempAABB$1.set(this.viewer.scene.aabb),math.getAABB3Center(tempAABB$1,tempVec3$2),tempAABB$1[0]+=t[0]-tempVec3$2[0],tempAABB$1[1]+=t[1]-tempVec3$2[1],tempAABB$1[2]+=t[2]-tempVec3$2[2],tempAABB$1[3]+=t[0]-tempVec3$2[0],tempAABB$1[4]+=t[1]-tempVec3$2[1],tempAABB$1[5]+=t[2]-tempVec3$2[2],this.viewer.cameraFlight.flyTo({aabb:tempAABB$1,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.error("Can't find overview canvas: '"+t.overviewCanvasId+"' - will create plugin without overview")}else this.error("Config missing: overviewCanvasId - will create plugin without overview");this._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",e=>{this._sectionPlaneCreated(e)})}setOverviewVisible(e){this._overview&&this._overview.setVisible(e)}getOverviewVisible(){if(this._overview)return this._overview.getVisible()}get sectionPlanes(){return this._sectionPlanes}createSectionPlane(e={}){return void 0!==e.id&&null!==e.id&&this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),new SectionPlane(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0})}_sectionPlaneCreated(e){const t=this._freeControls.length>0?this._freeControls.pop():new Control(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",()=>{this._sectionPlaneDestroyed(e)})}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}showControl(e){const t=this._controls[e];t?(this.hideControl(),t.setVisible(!0),this._overview&&this._overview.setPlaneSelected(e,!0),this._shownControlId=e):this.error("Control not found: "+e)}getShownControl(){return this._shownControlId}hideControl(){for(var e in this._controls)this._controls.hasOwnProperty(e)&&(this._controls[e].setVisible(!1),this._overview&&this._overview.setPlaneSelected(e,!1));this._shownControlId=null}destroySectionPlane(e){var t=this.viewer.scene.sectionPlanes[e];t?(this._sectionPlaneDestroyed(t),t.destroy(),e===this._shownControlId&&(this._shownControlId=null)):this.error("SectionPlane not found: "+e)}_sectionPlaneDestroyed(e){this._overview&&this._overview.removeSectionPlane(e);const t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}clear(){const e=Object.keys(this._sectionPlanes);for(var t=0,i=e.length;t{e.target.classList.contains("xeokit-context-menu-item")||this.hide()}),e.items&&(this.items=e.items),this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}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{const i=this._getNextId(),s=new Menu(i);for(let i=0,r=e.length;i0,l=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),d=i.getEnabled||(()=>!0),u=new Item(l,h,c,d);if(u.parentMenu=s,o.items.push(u),n){const e=t(a);u.subMenu=e,e.parentItem=u}this._itemList.push(u),this._itemMap[u.id]=u}}return this._menuList.push(s),this._menuMap[s.id]=s,s};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+" [MORE]"):i.push('
  • '+l+"
  • ")}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=(e=>{e.preventDefault()});const o=this;let a=null;if(t)for(let e=0,i=t.length;e{if(e.preventDefault(),!1===t.enabled)return;const i=t.subMenu;if(!i)return void(a&&(o._hideMenu(a.id),a=null));a&&a.id!==i.id&&(o._hideMenu(a.id),a=null);const s=t.itemElement,r=i.menuElement,n=s.getBoundingClientRect();r.getBoundingClientRect();n.right+200>window.innerWidth?o._showMenu(i.id,n.left-200,n.top-1):o._showMenu(i.id,n.right-5,n.top-1),a=i}),s||(t.itemElement.addEventListener("click",e=>{e.preventDefault(),o.hide(),o._context&&!1!==t.enabled&&t.doAction&&t.doAction(o._context)}),t.itemElement.addEventListener("mouseenter",e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)}))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}const tempAABB$2=math.AABB3(),tempVec3$3=math.vec3();class SectionToolContextMenu extends ContextMenu{constructor(e={}){if(!e.sectionPlanesPlugin)throw"Missing config: sectionPlanesPlugin";super(utils.apply({},e)),this._sectionPlanesPlugin=e.sectionPlanesPlugin,this._viewer=this._sectionPlanesPlugin.viewer,this._onSceneSectionPlaneCreated=this._viewer.scene.on("sectionPlaneCreated",()=>{this._buildMenu()}),this._onSceneSectionPlaneDestroyed=this._viewer.scene.on("sectionPlaneDestroyed",()=>{this._buildMenu()}),this._buildMenu()}_buildMenu(){const e=this._sectionPlanesPlugin,t=Object.values(e.sectionPlanes),i=[];for(let s=0,r=t.length;s"Slice #"+(s+1),doHoverEnter(t){e.hideControl(),e.showControl(r.id)},doHoverLeave(t){e.hideControl()},items:[[{getTitle:e=>"Edit",doAction:t=>{e.hideControl(),e.showControl(r.id);const i=r.pos;tempAABB$2.set(this._viewer.scene.aabb),math.getAABB3Center(tempAABB$2,tempVec3$3),tempAABB$2[0]+=i[0]-tempVec3$3[0],tempAABB$2[1]+=i[1]-tempVec3$3[1],tempAABB$2[2]+=i[2]-tempVec3$3[2],tempAABB$2[3]+=i[0]-tempVec3$3[0],tempAABB$2[4]+=i[1]-tempVec3$3[1],tempAABB$2[5]+=i[2]-tempVec3$3[2],this._viewer.cameraFlight.flyTo({aabb:tempAABB$2,fitFOV:65})}},{getTitle:e=>"Flip",doAction:e=>{r.flipDir()}},{getTitle:e=>"Delete",doAction:e=>{r.destroy()}}]]})}this.items=[[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}},{title:"Flip Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.flipSections()}}],i]}destroy(){super.destroy();const e=this._viewer.scene;e.off(this._onSceneSectionPlaneCreated),e.off(this._onSceneSectionPlaneDestroyed)}}class SectionTool extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";if(!t.menuButtonElement)throw"Missing config: menuButtonElement";this._buttonElement=t.buttonElement,this._counterElement=t.counterElement,this._menuButtonElement=t.menuButtonElement,this._menuButtonArrowElement=t.menuButtonArrowElement,this._sectionPlanesPlugin=new SectionPlanesPlugin(this.viewer,{}),this._sectionToolContextMenu=new SectionToolContextMenu({sectionPlanesPlugin:this._sectionPlanesPlugin,hideOnMouseDown:!1}),this._sectionPlanesPlugin.setOverviewVisible(!1),this.on("enabled",e=>{e?(this._buttonElement.classList.remove("disabled"),this._counterElement&&this._counterElement.classList.remove("disabled"),this._menuButtonElement.classList.remove("disabled"),this._menuButtonArrowElement.classList.remove("disabled")):(this._buttonElement.classList.add("disabled"),this._counterElement&&this._counterElement.classList.add("disabled"),this._menuButtonElement.classList.add("disabled"),this._menuButtonArrowElement.classList.add("disabled"))}),this.on("active",e=>{e?(this._buttonElement.classList.add("active"),this._counterElement&&this._counterElement.classList.add("active"),this._menuButtonElement.classList.add("active"),this._menuButtonArrowElement.classList.add("active")):(this._buttonElement.classList.remove("active"),this._counterElement&&this._counterElement.classList.remove("active"),this._menuButtonElement.classList.remove("active"),this._menuButtonArrowElement.classList.remove("active"))}),this.on("active",e=>{e||this._sectionPlanesPlugin.hideControl()}),this._buttonElement.addEventListener("click",e=>{if(!this.getEnabled())return;if(e.target===this._menuButtonElement||e.target.parentNode===this._menuButtonElement)return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),document.addEventListener("mousedown",e=>{if(!e.target.classList.contains("xeokit-context-menu-item"))if(e.target===this._menuButtonElement||e.target.parentNode===this._menuButtonElement)if(e.preventDefault(),this._sectionToolContextMenu.shown)this._sectionToolContextMenu.hide();else{this._sectionToolContextMenu.context={bimViewer:this.bimViewer,viewer:this.viewer,sectionTool:this};const e=this._menuButtonElement.getBoundingClientRect();this._sectionToolContextMenu.show(e.left,e.bottom+5)}else this._sectionToolContextMenu.hide()}),this._sectionToolContextMenu.on("shown",()=>{this._menuButtonArrowElement.classList.remove("xeokit-arrow-down"),this._menuButtonArrowElement.classList.add("xeokit-arrow-up")}),this._sectionToolContextMenu.on("hidden",()=>{this._menuButtonArrowElement.classList.remove("xeokit-arrow-up"),this._menuButtonArrowElement.classList.add("xeokit-arrow-down")}),this.bimViewer.on("reset",()=>{this.clear(),this.setActive(!1)}),this._initSectionMode()}_initSectionMode(){this.viewer.scene.input.on("mouseclicked",e=>{if(!this.getActive()||!this.getEnabled())return;const t=this.viewer.scene.pick({canvasPos:e,pickSurface:!0});if(t){const e=this._sectionPlanesPlugin.createSectionPlane({pos:t.worldPos,dir:math.mulVec3Scalar(t.worldNormal,-1)});e.on("destroyed",()=>{this._updateSectionPlanesCount()}),this._sectionPlanesPlugin.showControl(e.id),this._updateSectionPlanesCount()}}),this._updateSectionPlanesCount()}_updateSectionPlanesCount(){this._counterElement&&(this._counterElement.innerText=""+this.getNumSections())}getNumSections(){return Object.keys(this._sectionPlanesPlugin.sectionPlanes).length}clear(){this._sectionPlanesPlugin.clear(),this._updateSectionPlanesCount()}flipSections(){this._sectionPlanesPlugin.flipSectionPlanes()}destroy(){this._sectionPlanesPlugin.destroy(),this._sectionToolContextMenu.destroy(),super.destroy()}}const webglEnums={funcAdd:"FUNC_ADD",funcSubtract:"FUNC_SUBTRACT",funcReverseSubtract:"FUNC_REVERSE_SUBTRACT",zero:"ZERO",one:"ONE",srcColor:"SRC_COLOR",oneMinusSrcColor:"ONE_MINUS_SRC_COLOR",dstColor:"DST_COLOR",oneMinusDstColor:"ONE_MINUS_DST_COLOR",srcAlpha:"SRC_ALPHA",oneMinusSrcAlpha:"ONE_MINUS_SRC_ALPHA",dstAlpha:"DST_ALPHA",oneMinusDstAlpha:"ONE_MINUS_DST_ALPHA",contantColor:"CONSTANT_COLOR",oneMinusConstantColor:"ONE_MINUS_CONSTANT_COLOR",constantAlpha:"CONSTANT_ALPHA",oneMinusConstantAlpha:"ONE_MINUS_CONSTANT_ALPHA",srcAlphaSaturate:"SRC_ALPHA_SATURATE",front:"FRONT",back:"BACK",frontAndBack:"FRONT_AND_BACK",never:"NEVER",less:"LESS",equal:"EQUAL",lequal:"LEQUAL",greater:"GREATER",notequal:"NOTEQUAL",gequal:"GEQUAL",always:"ALWAYS",cw:"CW",ccw:"CCW",linear:"LINEAR",nearest:"NEAREST",linearMipmapNearest:"LINEAR_MIPMAP_NEAREST",nearestMipmapNearest:"NEAREST_MIPMAP_NEAREST",nearestMipmapLinear:"NEAREST_MIPMAP_LINEAR",linearMipmapLinear:"LINEAR_MIPMAP_LINEAR",repeat:"REPEAT",clampToEdge:"CLAMP_TO_EDGE",mirroredRepeat:"MIRRORED_REPEAT",alpha:"ALPHA",rgb:"RGB",rgba:"RGBA",luminance:"LUMINANCE",luminanceAlpha:"LUMINANCE_ALPHA",textureBinding2D:"TEXTURE_BINDING_2D",textureBindingCubeMap:"TEXTURE_BINDING_CUBE_MAP",compareRToTexture:"COMPARE_R_TO_TEXTURE",unsignedByte:"UNSIGNED_BYTE"};function getGLEnum(e,t,i){if(void 0===t)return i;const s=webglEnums[t];return void 0===s?i:e[s]}const color$1=new Uint8Array([0,0,0,1]);class Texture2D{constructor(e,t){this.gl=e,this.target=t||e.TEXTURE_2D,this.texture=e.createTexture(),this.setPreloadColor([0,0,0,0]),this.allocated=!0}setPreloadColor(e){e?(color$1[0]=Math.floor(255*e[0]),color$1[1]=Math.floor(255*e[1]),color$1[2]=Math.floor(255*e[2]),color$1[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(color$1[0]=0,color$1[1]=0,color$1[2]=0,color$1[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,t.NEAREST),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>t;return e+1}class Texture extends Component{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new RenderState({texture:new Texture2D(this.scene.canvas.gl),matrix:math.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=math.vec2([0,0]),this._scale=math.vec2([1,1]),this._rotate=math.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),stats.memory.textures++}_checkMinFilter(e){return"linear"!==(e=e||"linearMipmapLinear")&&"linearMipmapNearest"!==e&&"linearMipmapLinear"!==e&&"nearestMipmapLinear"!==e&&"nearestMipmapNearest"!==e&&(this.error("Unsupported value for 'minFilter': '"+e+"' - supported values are 'linear', 'linearMipmapNearest', 'nearestMipmapNearest', 'nearestMipmapLinear' and 'linearMipmapLinear'. Defaulting to 'linearMipmapLinear'."),e="linearMipmapLinear"),e}_checkMagFilter(e){return"linear"!==(e=e||"linear")&&"nearest"!==e&&(this.error("Unsupported value for 'magFilter': '"+e+"' - supported values are 'linear' and 'nearest'. Defaulting to 'linear'."),e="linear"),e}_checkFilter(e){return"linear"!==(e=e||"linear")&&"nearest"!==e&&(this.error("Unsupported value for 'magFilter': '"+e+"' - supported values are 'linear' and 'nearest'. Defaulting to 'linear'."),e="linear"),e}_checkWrapS(e){return"clampToEdge"!==(e=e||"repeat")&&"mirroredRepeat"!==e&&"repeat"!==e&&(this.error("Unsupported value for 'wrapS': '"+e+"' - supported values are 'clampToEdge', 'mirroredRepeat' and 'repeat'. Defaulting to 'repeat'."),e="repeat"),e}_checkWrapT(e){return"clampToEdge"!==(e=e||"repeat")&&"mirroredRepeat"!==e&&"repeat"!==e&&(this.error("Unsupported value for 'wrapT': '"+e+"' - supported values are 'clampToEdge', 'mirroredRepeat' and 'repeat'. Defaulting to 'repeat'."),e="repeat"),e}_checkFlipY(e){return!!e}_checkEncoding(e){return"linear"!==(e=e||"linear")&&"sRGB"!==e&&"gamma"!==e&&(this.error("Unsupported value for 'encoding': '"+e+"' - supported values are 'linear', 'sRGB', 'gamma'. Defaulting to 'linear'."),e="linear"),e}_webglContextRestored(){this._state.texture=new Texture2D(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=math.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=math.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?math.mulMat4(t,i):i),0!==this._rotate&&(i=math.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?math.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=ensureImageSizePowerOfTwo(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._state.texture.setProps(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=ensureImageSizePowerOfTwo(i),t._state.texture.setImage(i,t._state),t._state.texture.setProps(t._state),t.scene.loading--,t.scene.canvas.spinner.processes--,t.glRedraw()},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(),stats.memory.textures--}}function CubeTextureCanvas(e,t={}){const i="lightgrey",s=t.hoverColor||"rgba(0,0,0,0.4)";var r=500+500/3,o=r/24;const a=[{boundary:[6,6,6,6],color:t.frontColor||t.color||"#55FF55"},{boundary:[18,6,6,6],color:t.backColor||t.color||"#55FF55"},{boundary:[12,6,6,6],color:t.leftColor||t.color||"#FF5555"},{boundary:[0,6,6,6],color:t.rightColor||t.color||"#FF5555"},{boundary:[6,0,6,6],color:t.topColor||t.color||"#7777FF"},{boundary:[6,12,6,6],color:t.bottomColor||t.color||"#7777FF"}],n=[{label:"front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"bottom",boundaries:[[7,13,4,4]],dir:[0,0,1],up:[0,-1,0]},{boundaries:[[7,5,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,0,-1],up:[1,0,1]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,-1],up:[0,-1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,0,-1],up:[-1,0,1]},{boundaries:[[7,11,4,2]],dir:[0,1,1],up:[0,-1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,0,1],up:[-1,0,1]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,0,1],up:[1,0,1]},{boundaries:[[5,7,2,4]],dir:[1,1,0],up:[0,0,1]},{boundaries:[[11,7,2,4]],dir:[-1,1,0],up:[0,0,1]},{boundaries:[[17,7,2,4]],dir:[-1,-1,0],up:[0,0,1]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,-1,0],up:[0,0,1]},{boundaries:[[5,11,2,2]],dir:[1,1,1],up:[-1,-1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,-1,1],up:[-1,1,1]},{boundaries:[[5,5,2,2]],dir:[1,1,-1],up:[1,1,1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,-1,1],up:[1,1,1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,-1],up:[-1,-1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,1],up:[1,-1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,-1],up:[1,-1,1]},{boundaries:[[11,5,2,2]],dir:[-1,1,-1],up:[-1,1,1]}],l=(t.frontColor||t.color,t.backColor||t.color,t.leftColor||t.color,t.rightColor||t.color,t.topColor||t.color,t.bottomColor||t.color,[{label:"front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-1,-1],up:[0,1,-1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,-1,0],up:[1,1,0]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,-1,0],up:[-1,1,0]},{boundaries:[[7,11,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,1,0],up:[-1,1,0]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,1,1],up:[0,1,-1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,1,0],up:[1,1,0]},{boundaries:[[5,7,2,4]],dir:[1,0,-1],up:[0,1,0]},{boundaries:[[11,7,2,4]],dir:[-1,0,-1],up:[0,1,0]},{boundaries:[[17,7,2,4]],dir:[-1,0,1],up:[0,1,0]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,0,1],up:[0,1,0]},{boundaries:[[5,11,2,2]],dir:[1,1,-1],up:[-1,1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,1,1],up:[-1,1,-1]},{boundaries:[[5,5,2,2]],dir:[1,-1,-1],up:[1,1,-1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,1,1],up:[1,1,-1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,1],up:[-1,1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,-1],up:[1,1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,1],up:[1,1,1]},{boundaries:[[11,5,2,2]],dir:[-1,-1,-1],up:[-1,1,-1]}]);for(let e=0,t=n.length;e=r[0]*o&&t<=(r[0]+r[2])*o&&i>=r[1]*o&&i<=(r[1]+r[3])*o)return s}}return-1},this.setAreaHighlighted=function(e,t){var i=h[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,d()},this.getAreaDir=function(e){var t=h[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=h[e];if(!t)throw"Unknown area: "+e;return t.up},this.getImage=function(){return this._textureCanvas},this.destroy=function(){this._textureCanvas&&(this._textureCanvas.parentNode.removeChild(this._textureCanvas),this._textureCanvas=null)},this.clear()}class NavCubePlugin extends Plugin{constructor(e,t={}){super("NavCube",e,t),e.navCube=this;try{this._navCubeScene=new Scene({canvasId:t.canvasId,canvasElement:t.canvasElement,transparent:!0}),this._navCubeCanvas=this._navCubeScene.canvas.canvas,this._navCubeScene.input.keyboardEnabled=!1}catch(e){return void this.error(e)}const i=this._navCubeScene;i.clearLights(),new DirLight(i,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new DirLight(i,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new DirLight(i,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._navCubeCamera=i.camera,this._navCubeCamera.ortho.scale=7,this._navCubeCamera.ortho.near=.1,this._navCubeCamera.ortho.far=2e3,this._zUp=Boolean(e.camera.zUp);var s,r,o,a,n=this;this._synchCamera=(s=math.rotationMat4c(-90*math.DEGTORAD,1,0,0),r=math.vec3(),o=math.vec3(),a=math.vec3(),function(){var t=e.camera.eye,i=e.camera.look,l=e.camera.up;r=math.mulVec3Scalar(math.normalizeVec3(math.subVec3(t,i,r)),5),n._zUp?(math.transformVec3(s,r,o),math.transformVec3(s,l,a),n._navCubeCamera.look=[0,0,0],n._navCubeCamera.eye=math.transformVec3(s,r,o),n._navCubeCamera.up=math.transformPoint3(s,l,a)):(n._navCubeCamera.look=[0,0,0],n._navCubeCamera.eye=r,n._navCubeCamera.up=l)}),this._cubeTextureCanvas=new CubeTextureCanvas(e,t),this._cubeSampler=new Texture(i,{image:this._cubeTextureCanvas.getImage(),flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge"}),this._cubeMesh=new Mesh(i,{geometry:new ReadableGeometry(i,{primitive:"triangles",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],positions:[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],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],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]}),material:new PhongMaterial(i,{diffuse:[.4,.4,.4],specular:[.4,.4,.4],emissive:[.6,.6,.6],diffuseMap:this._cubeSampler,emissiveMap:this._cubeSampler}),visible:!0,edges:!0}),this._shadow=new Mesh(i,{geometry:new ReadableGeometry(i,buildCylinderGeometry({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new PhongMaterial(i,{diffuse:[0,0,0],specular:[0,0,0],emissive:[0,0,0],alpha:.5}),position:[0,-1.5,0],visible:!0,pickable:!1,backfaces:!1}),this._onCameraMatrix=e.camera.on("matrix",this._synchCamera),this._onCameraWorldAxis=e.camera.on("worldAxis",()=>{e.camera.zUp?(this._zUp=!0,this._cubeTextureCanvas.setZUp(),this._repaint(),this._synchCamera()):e.camera.yUp&&(this._zUp=!1,this._cubeTextureCanvas.setYUp(),this._repaint(),this._synchCamera())}),this._onCameraFOV=e.camera.perspective.on("fov",e=>{this._synchProjection&&(this._navCubeCamera.perspective.fov=e)}),this._onCameraProjection=e.camera.on("projection",e=>{this._synchProjection&&(this._navCubeCamera.projection=e)});var l=-1;function h(e){var t=[0,0];if(e){for(var i=e.target,s=0,r=0;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}var c,d,u=null,p=null,m=!1,_=!1,f=.5;n._navCubeCanvas.addEventListener("mouseenter",n._onMouseEnter=function(e){_=!0}),n._navCubeCanvas.addEventListener("mouseleave",n._onMouseLeave=function(e){_=!1}),n._navCubeCanvas.addEventListener("mousedown",n._onMouseDown=function(e){if(1===e.which){u=e.x,p=e.y,c=e.clientX,d=e.clientY;var t=h(e),s=i.pick({canvasPos:t});m=!!s}}),document.addEventListener("mouseup",n._onMouseUp=function(e){if(1===e.which&&(m=!1,null!==u)){var t=h(e),s=i.pick({canvasPos:t,pickSurface:!0});if(s&&s.uv){var r=n._cubeTextureCanvas.getArea(s.uv);if(r>=0&&(document.body.style.cursor="pointer",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),r>=0)){if(n._cubeTextureCanvas.setAreaHighlighted(r,!0),l=r,n._repaint(),e.xu+3||e.yp+3)return;var o=n._cubeTextureCanvas.getAreaDir(r);if(o){var a=n._cubeTextureCanvas.getAreaUp(r);v(o,a,function(){l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1);var e=i.pick({canvasPos:t,pickSurface:!0});if(e&&e.uv){var s=n._cubeTextureCanvas.getArea(e.uv);void 0!==s&&(document.body.style.cursor="pointer",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),s>=0&&(n._cubeTextureCanvas.setAreaHighlighted(s,!0),l=s,n._repaint()))}})}}}}}),document.addEventListener("mousemove",n._onMouseMove=function(t){if(l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),1!==t.buttons||m){if(m){var s=t.clientX,r=t.clientY;return document.body.style.cursor="move",void function(t,i){var s=(t-c)*-f,r=(i-d)*-f;e.camera.orbitYaw(s),e.camera.orbitPitch(-r),c=t,d=i}(s,r)}if(_){var o=h(t),a=i.pick({canvasPos:o,pickSurface:!0});if(a){if(a.uv){document.body.style.cursor="pointer";var u=n._cubeTextureCanvas.getArea(a.uv);if(u===l)return;l>=0&&n._cubeTextureCanvas.setAreaHighlighted(l,!1),u>=0&&(n._cubeTextureCanvas.setAreaHighlighted(u,!0),n._repaint(),l=u)}}else document.body.style.cursor="default",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1)}}});var g,v=(g=math.vec3(),function(t,i,s){var r=n._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,o=math.getAABB3Diag(r);math.getAABB3Center(r,g);var a=Math.abs(o/Math.tan(27.5));e.cameraControl.pivotPos=g,n._cameraFly?e.cameraFlight.flyTo({look:g,eye:[g[0]-a*t[0],g[1]-a*t[1],g[2]-a*t[2]],up:i||[0,1,0],orthoScale:1.3*o,fitFOV:n._cameraFitFOV,duration:n._cameraFlyDuration},s):e.cameraFlight.jumpTo({look:g,eye:[g[0]-a*t[0],g[1]-a*t[1],g[2]-a*t[2]],up:i||[0,1,0],orthoScale:1.3*o,fitFOV:n._cameraFitFOV},s)});this.setVisible(t.visible),this.setCameraFitFOV(t.cameraFitFOV),this.setCameraFly(t.cameraFly),this.setCameraFlyDuration(t.cameraFlyDuration),this.setFitVisible(t.fitVisible),this.setSynchProjection(t.synchProjection)}send(e,t){switch(e){case"language":this._cubeTextureCanvas.clear(),this._repaint()}}_repaint(){const e=this._cubeTextureCanvas.getImage();this._cubeMesh.material.diffuseMap.image=e,this._cubeMesh.material.emissiveMap.image=e}setVisible(e=!0){this._navCubeCanvas&&(this._cubeMesh.visible=e,this._shadow.visible=e,this._navCubeCanvas.style.visibility=e?"visible":"hidden")}getVisible(){return!!this._navCubeCanvas&&this._cubeMesh.visible}setFitVisible(e=!1){this._fitVisible=e}getFitVisible(){return this._fitVisible}setCameraFly(e=!0){this._cameraFly=e}getCameraFly(){return this._cameraFly}setCameraFitFOV(e=45){this._cameraFitFOV=e}getCameraFitFOV(){return this._cameraFitFOV}setCameraFlyDuration(e=.5){this._cameraFlyDuration=e}getCameraFlyDuration(){return this._cameraFlyDuration}setSynchProjection(e=!1){this._synchProjection=e}getSynchProjection(){return this._synchProjection}destroy(){this._navCubeCanvas&&(this.viewer.camera.off(this._onCameraMatrix),this.viewer.camera.off(this._onCameraWorldAxis),this.viewer.camera.perspective.off(this._onCameraFOV),this.viewer.camera.off(this._onCameraProjection),this._navCubeCanvas.removeEventListener("mouseenter",this._onMouseEnter),this._navCubeCanvas.removeEventListener("mouseleave",this._onMouseLeave),this._navCubeCanvas.removeEventListener("mousedown",this._onMouseDown),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),this._navCubeCanvas=null,this._cubeTextureCanvas.destroy(),this._cubeTextureCanvas=null,this._onMouseEnter=null,this._onMouseLeave=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null),this._navCubeScene.destroy(),this._navCubeScene=null,this._cubeMesh=null,this._shadow=null,super.destroy()}}class NavCubeMode extends Controller{constructor(e,t){if(super(e,t),!t.navCubeCanvasElement)throw"Missing config: navCubeCanvasElement";const i=t.navCubeCanvasElement;this._navCube=new NavCubePlugin(this.viewer,{canvasElement:i,fitVisible:!0,color:"#CFCFCF"}),this._navCube.setVisible(this._active),this.on("active",e=>{this._navCube.setVisible(e)})}destroy(){this._navCube.destroy(),super.destroy()}}class PerformanceMesh{constructor(e,t,i,s,r=null,o=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.pickId=this.model.scene._renderer.getPickID(this),this.aabb=math.AABB3(),this._layer=r,this._portionId=o,this._color=[i[0],i[1],i[2],s],this._colorize=[i[0],i[1],i[2],s],this._colorizing=!1,this.numTriangles=0,this.rtcCenter=null}_initFlags(e){this._layer.initFlags(this._portionId,e)}_setVisible(e){this._layer.setVisible(this._portionId,e)}_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,!1),this._colorizing=!0):(this._layer.setColor(this._portionId,this._color,!1),this._colorizing=!1)}_setOpacity(e){this._color[3]=e,this._colorize[3]=e;this._colorizing?this._layer.setColor(this._portionId,this._colorize,!0):this._layer.setColor(this._portionId,this._color,!0)}_setOffset(e){this._layer.setOffset(this._portionId,e)}_setHighlighted(e){this._layer.setHighlighted(this._portionId,e)}_setXRayed(e){this._layer.setXRayed(this._portionId,e)}_setSelected(e){this._layer.setSelected(this._portionId,e)}_setEdges(e){this._layer.setEdges(this._portionId,e)}_setClippable(e){this._layer.setClippable(this._portionId,e)}_setCollidable(e){this._layer.setCollidable(this._portionId,e)}_setPickable(e){this._layer.setPickable(this._portionId,e)}_setCulled(e){this._layer.setCulled(this._portionId,e)}canPickTriangle(){return!1}drawPickTriangles(e){}pickTriangleSurface(e){}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const RENDER_FLAGS={VISIBLE:1,CULLED:4,PICKABLE:8,CLIPPABLE:16,COLLIDABLE:32,CAST_SHADOW:64,RECEIVE_SHADOW:128,XRAYED:256,HIGHLIGHTED:512,SELECTED:1024,EDGES:2048,BACKFACES:4096},tempFloatRGB=new Float32Array([0,0,0]),tempIntRGB=new Uint16Array([0,0,0]);class PerformanceNode{constructor(e,t,i,s,r,o){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=s,this._numTriangles=0;for(var a=0,n=this.meshes.length;a1&&(e=1),e=Math.floor(255*e),this.meshes[0]._colorize[3]/255===e)return}else e=255;for(let t=0,i=this.meshes.length;t0?this.meshes[0]._colorize[3]/255: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.meshes.length;e{batchingLayerScratchMemory._clear()}),batchingLayerScratchMemory}const RENDER_PASSES={NORMAL_OPAQUE:0,NORMAL_TRANSPARENT:1,NORMAL_EDGES:2,HIGHLIGHTED:3,HIGHLIGHTED_EDGES:4,XRAYED:5,XRAYED_EDGES:6,SELECTED:7,SELECTED_EDGES:8},BatchingDrawShaderSource=function(e,t){this.vertex=buildVertex$6(e),this.fragment=buildFragment$6(e,t)};function buildVertex$6(e){const t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0;let r,o,a;const n=[];for(n.push("// Batched geometry drawing vertex shader"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),n.push("attribute vec3 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("attribute vec3 offset;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),n.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vColor;"),n.push("void main(void) {"),n.push("bool visible = (float(flags.x) > 0.0);"),n.push("bool xrayed = (float(flags.y) > 0.0);"),n.push("bool highlighted = (float(flags.z) > 0.0);"),n.push("bool selected = (float(flags.w) > 0.0);"),n.push("bool culled = (float(flags2.w) > 0.0);"),n.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),n.push(`if (\n culled || !visible || \n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),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;"),r=0,o=i.lights.length;r0,a=[];if(a.push("// Batched geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),o)for(a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),s=0,r=i.sectionPlanes.length;s 0.0);"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,r=i.sectionPlanes.length;s 0.0) { discard; }"),a.push("}")}return t?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push(" gl_FragColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" gl_FragColor = vColor;"),a.push("}"),a}const tempVec4$1=math.vec4(),tempVec3a$9=math.vec3();class BatchingDrawRenderer{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._shaderSource=new BatchingDrawShaderSource(this._scene,this._withSAO),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=t.model,o=s.canvas.gl,a=t._state,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e),l=!0),o.uniformMatrix4fv(this._uViewMatrix,!1,n?createRTCViewMat(r.viewMatrix,n):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=r.renderFlags;for(let t=0;t0),s=[];return s.push("// Batched fill vertex shader"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec4 color;"),i&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("bool visible = (float(flags.x) > 0.0);"),s.push("bool xrayed = (float(flags.y) > 0.0);"),s.push("bool highlighted = (float(flags.z) > 0.0);"),s.push("bool selected = (float(flags.w) > 0.0);"),s.push("bool clippable = (float(flags2.x) > 0.0);"),s.push("bool culled = (float(flags2.w) > 0.0);"),s.push("bool transparent = (color.a < 1.0);"),s.push(`if (\n culled || !visible ||\n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),i&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2;")),s.push("gl_Position = projMatrix * viewPosition;"),s.push("}"),s.push("}"),s}function buildFragment$7(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Batched fill 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i 0.0) { discard; }"),o.push("}")}return o.push("gl_FragColor = color;"),o.push("}"),o}const defaultColor=new Float32Array([1,1,1]),tempVec3a$a=math.vec3();class BatchingFillRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingFillShaderSource(this._scene),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.canvas.gl,a=t._state,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0);const h=n?createRTCViewMat(s.viewMatrix,n):s.viewMatrix;if(o.uniformMatrix4fv(this._uViewMatrix,!1,h),o.uniformMatrix4fv(this._uModelMatrix,!1,s.worldMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("uniform vec4 color;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool highlighted = (float(flags.z) > 0.0);"),i.push("bool selected = (float(flags.w) > 0.0);"),i.push("bool edges = (float(flags2.y) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("bool transparent = (color.a < 1.0);"),i.push(`if (\n culled || !visible ||\n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (!edges || transparent || xrayed)) ||\n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!edges || !transparent || xrayed || highlighted || selected)) ||\n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) ||\n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$8(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Batched geometry 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i 0.0) { discard; }"),o.push("}")}return o.push("gl_FragColor = color;"),o.push("}"),o}const tempVec3a$b=math.vec3();class BatchingEdgesRenderer{constructor(e){this._scene=e,this._shaderSource=new BatchingEdgesShaderSource(this._scene),this._allocate(),this._hash=this._getHash()}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.canvas.gl,a=t._state,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0);const h=n?createRTCViewMat(s.viewMatrix,n):s.viewMatrix;if(o.uniformMatrix4fv(this._uViewMatrix,!1,h),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry picking vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 pickColor;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vPickColor;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool pickable = (float(flags2.z) > 0.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || (!pickInvisible && !visible) || !pickable) {"),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.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(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$9(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = vPickColor; "),s.push("}"),s}const tempVec3a$c=math.vec3();class BatchingPickMeshRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickMeshShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=t._state.rtcCenter;this._program||this._allocate(t);let n=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e),n=!0);const l=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,h=a?createRTCViewMat(l,a):l;if(r.uniformMatrix4fv(this._uViewMatrix,!1,h),a?e.lastRTCCenter&&math.compareVec3(a,e.lastRTCCenter)||(e.lastRTCCenter=a,n=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,n=!0),n){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool pickable = (float(flags2.z) > 0.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || (!pickInvisible && !visible) || !pickable) {"),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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$a(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),s.push("uniform float zNear;"),s.push("uniform float zFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" float zNormalizedDepth = abs((zNear + vViewPosition.z) / (zFar - zNear));"),s.push(" gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}const tempVec3a$d=math.vec3();class BatchingPickDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=s.camera.project._state,n=t._state.rtcCenter;this._program||this._allocate();let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniform1i(this._uPickInvisible,e.pickInvisible);const h=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,c=n?createRTCViewMat(h,n):h;if(r.uniformMatrix4fv(this._uViewMatrix,!1,c),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.uniform1f(this._uZNear,a.near),r.uniform1f(this._uZFar,a.far),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry normals vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vWorldNormal;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool pickable = (float(flags2.z) > 0.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || (!pickInvisible && !visible) || !pickable) {"),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.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(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$b(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}const tempVec3a$e=math.vec3();class BatchingPickNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=t._state.rtcCenter;this._program||this._allocate(t);let n=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),n=!0),r.uniform1i(this._uPickInvisible,e.pickInvisible);const l=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,h=a?createRTCViewMat(l,a):l;if(r.uniformMatrix4fv(this._uViewMatrix,!1,h),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),a?e.lastRTCCenter&&math.compareVec3(a,e.lastRTCCenter)||(e.lastRTCCenter=a,n=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,n=!0),n){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched occlusion vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (culled || !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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$c(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched 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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}const tempVec3a$f=math.vec3();class BatchingOcclusionRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingOcclusionShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=s.camera,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0);const h=n?createRTCViewMat(i.viewMatrix,n):i.viewMatrix;if(r.uniformMatrix4fv(this._uViewMatrix,!1,h),r.uniformMatrix4fv(this._uProjMatrix,!1,a._project._state.matrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool xrayed = (float(flags.y) > 0.0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || !visible || transparent || xrayed) {"),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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$d(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = packDepthToRGBA( gl_FragCoord.z); "),s.push("}"),s}const tempVec3a$g=math.vec3();class BatchingDepthRenderer{constructor(e){this._scene=e,this._shaderSource=new BatchingDepthShaderSource(this._scene),this._allocate(this._scene),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let n=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),n=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,a?createRTCViewMat(i.viewMatrix,a):i.viewMatrix),a?e.lastRTCCenter&&math.compareVec3(a,e.lastRTCCenter)||(e.lastRTCCenter=a,n=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,n=!0),n){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry normals vertex shader"),i.push("attribute vec3 position;"),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 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool xrayed = (float(flags.y) > 0.0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || !visible || transparent || xrayed) {"),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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = 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(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$e(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}const tempVec3a$h=math.vec3(),tempMat4a=math.mat4();class BatchingNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let n=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t),n=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,a?createRTCViewMat(i.viewMatrix,a):i.viewMatrix),r.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),a?e.lastRTCCenter&&math.compareVec3(a,e.lastRTCCenter)||(e.lastRTCCenter=a,n=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,n=!0),n){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry shadow vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$f(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}const tempVec3a$i=math.vec3();class BatchingShadowRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingShadowShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=this._scene,s=i.canvas.gl,r=t._state;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aColor&&this._aColor.bindArrayBuffer(r.colorsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(r.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(r.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(r.offsetsBuf),r.indicesBuf.bind();const o=i._sectionPlanesState.sectionPlanes.length;if(o>0){const e=i._sectionPlanesState.sectionPlanes,r=t.layerIndex*o,a=model.renderFlags,n=t._state.rtcCenter;for(let t=0;t{i._compile()}),e.on("destroyed",()=>{delete sceneBatchingRenderers[t],i._destroy()})),i}const bigIndicesSupported$1=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,MAX_VERTS=bigIndicesSupported$1?5e6:65530,MAX_INDICES=3*MAX_VERTS;class BatchingBuffer{constructor(){this.maxVerts=MAX_VERTS,this.maxIndices=MAX_INDICES,this.positions=[],this.colors=[],this.normals=[],this.pickColors=[],this.flags=[],this.flags2=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const tempMat4=math.mat4(),tempMat4b=math.mat4(),tempVec4a=math.vec4([0,0,0,1]),tempVec4b=math.vec4([0,0,0,1]),tempVec4c=math.vec4([0,0,0,1]),tempOBB3=math.OBB3();class BatchingLayer{constructor(e,t){this.layerIndex=t.layerIndex,this._batchingRenderers=getBatchingRenderers(e.scene),this.model=e,this._buffer=new BatchingBuffer,this._scratchMemory=t.scratchMemory;var i,s=t.primitive||"triangles";const r=e.scene.canvas.gl;switch(s){case"points":i=r.POINTS;break;case"lines":i=r.LINES;break;case"line-loop":i=r.LINE_LOOP;break;case"line-strip":i=r.LINE_STRIP;break;case"triangles":i=r.TRIANGLES;break;case"triangle-strip":i=r.TRIANGLE_STRIP;break;case"triangle-fan":i=r.TRIANGLE_FAN;break;default:e.error(`Unsupported value for 'primitive': '${s}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),i=r.TRIANGLES,s="triangles"}this._state=new RenderState({primitiveName:s,primitive:i,positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,flagsBuf:null,flags2Buf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:math.mat4(),rtcCenter: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=math.collapseAABB3(),this._portions=[],this._finalized=!1,this._positionsDecodeMatrix=t.positionsDecodeMatrix,this._preCompressed=!!this._positionsDecodeMatrix,t.rtcCenter&&(this._state.rtcCenter=math.vec3(t.rtcCenter)),this.aabb=math.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)if(this._preCompressed){e.positionsDecodeMatrix=this._positionsDecodeMatrix;const s=new Uint16Array(i.positions);e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=new Float32Array(i.positions),r=new Uint16Array(s.length);quantizePositions(s,i.positions.length,this._modelAABB,r,e.positionsDecodeMatrix),e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}if(i.normals.length>0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new ArrayBuf(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 ArrayBuf(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.flags.length>0){const s=new Uint8Array(i.flags),r=new Uint8Array(i.flags2);let o=!0;e.flagsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,i.flags.length,4,t.DYNAMIC_DRAW,o),e.flags2Buf=new ArrayBuf(t,t.ARRAY_BUFFER,r,i.flags.length,4,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}const s=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint;if(i.indices.length>0){const r=s?new Uint32Array(i.indices):new Uint16Array(i.indices);e.indicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,r,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const r=s?new Uint32Array(i.edgeIndices):new Uint16Array(i.edgeIndices);e.edgeIndicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,r,i.edgeIndices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t){t&RENDER_FLAGS.VISIBLE&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&RENDER_FLAGS.HIGHLIGHTED&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&RENDER_FLAGS.XRAYED&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&RENDER_FLAGS.SELECTED&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&RENDER_FLAGS.CLIPPABLE&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&RENDER_FLAGS.EDGES&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&RENDER_FLAGS.PICKABLE&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&RENDER_FLAGS.CULLED&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),this._setFlags(e,t),this._setFlags2(e,t)}setVisible(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.VISIBLE?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t)}setHighlighted(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.HIGHLIGHTED?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t)}setXRayed(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.XRAYED?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t)}setSelected(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.SELECTED?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t)}setEdges(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.EDGES?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags2(e,t)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.CLIPPABLE?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCulled(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.CULLED?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.PICKABLE?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t)}setColor(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=2*e,r=4*this._portions[s],o=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(o),n=t[0],l=t[1],h=t[2],c=t[3];for(var d=0;dh&&(n=o,h=l),(l=dot$1(u,a=octDecodeVec2$1(o=octEncodeVec3$1(u,"floor","ceil"))))>h&&(n=o,h=l),(l=dot$1(u,a=octDecodeVec2$1(o=octEncodeVec3$1(u,"ceil","ceil"))))>h&&(n=o,h=l),s[r+c+0]=n[0],s[r+c+1]=n[1],s[r+c+2]=0;return r+=i}function octEncodeVec3$1(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 octDecodeVec2$1(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 dot$1(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}const InstancingDrawShaderSource=function(e,t){this.vertex=buildVertex$g(e),this.fragment=buildFragment$g(e,t)};function buildVertex$g(e){const t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0;let r,o,a;const n=[];for(n.push("// Instancing geometry drawing vertex shader"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),n.push("attribute vec2 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("attribute vec3 offset;"),n.push("attribute vec4 modelMatrixCol0;"),n.push("attribute vec4 modelMatrixCol1;"),n.push("attribute vec4 modelMatrixCol2;"),n.push("attribute vec4 modelNormalMatrixCol0;"),n.push("attribute vec4 modelNormalMatrixCol1;"),n.push("attribute vec4 modelNormalMatrixCol2;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),n.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vColor;"),n.push("void main(void) {"),n.push("bool visible = (float(flags.x) > 0.0);"),n.push("bool xrayed = (float(flags.y) > 0.0);"),n.push("bool highlighted = (float(flags.z) > 0.0);"),n.push("bool selected = (float(flags.w) > 0.0);"),n.push("bool culled = (float(flags2.w) > 0.0);"),n.push("bool transparent = (float(color.a) < 255.0);"),n.push(`if \n (culled || !visible || \n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec4 worldNormal = vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),n.push("vec3 viewNormal = normalize(vec4(worldNormal * viewNormalMatrix).xyz);"),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;"),r=0,o=i.lights.length;r0,a=[];if(a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),o)for(a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),s=0,r=i.sectionPlanes.length;s 0.0);"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,r=i.sectionPlanes.length;s 0.0) { discard; }"),a.push("}")}return t?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push(" gl_FragColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" gl_FragColor = vColor;"),a.push("}"),a}const tempVec4$2=math.vec4(),tempVec3a$j=math.vec3(),tempMat4a$1=math.mat4(),tempMat4b$1=math.mat4();class InstancingDrawRenderer{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._shaderSource=new InstancingDrawShaderSource(this._scene,this._withSAO),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=t.model,r=s.scene,o=r.canvas.gl,a=t._state,n=this._instanceExt,l=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let h=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e),h=!0),o.uniformMatrix4fv(this._uViewMatrix,!1,l?createRTCViewMat(s.viewMatrix,l):s.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,s.viewNormalMatrix),l?e.lastRTCCenter&&math.compareVec3(l,e.lastRTCCenter)||(e.lastRTCCenter=l,h=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,h=!0),h){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,n=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing fill vertex shader"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),i.push("uniform vec4 color;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool highlighted = (float(flags.z) > 0.0);"),i.push("bool selected = (float(flags.w) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("bool transparent = (color.a < 1.0);"),i.push(`if (\n culled || !visible ||\n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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);"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$h(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e 0.0) { discard; }"),s.push("}")}return s.push("gl_FragColor = color;"),s.push("}"),s}const tempVec3a$k=math.vec3();class InstancingFillRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingFillShaderSource(this._scene),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.canvas.gl,a=t._state,n=this._instanceExt,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t.model.scene),this.errors))return;let h=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),h=!0),o.uniformMatrix4fv(this._uViewMatrix,!1,l?createRTCViewMat(s.viewMatrix,l):s.viewMatrix),l?e.lastRTCCenter&&math.compareVec3(l,e.lastRTCCenter)||(e.lastRTCCenter=l,h=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,h=!0),h){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,n=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing edges vertex shader"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("uniform vec4 color;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool highlighted = (float(flags.z) > 0.0);"),i.push("bool selected = (float(flags.w) > 0.0);"),i.push("bool edges = (float(flags2.y) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("bool transparent = (color.a < 1.0);"),i.push(`if (\n culled || !visible || \n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (!edges || transparent || xrayed)) ||\n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!edges || !transparent || xrayed || highlighted || selected)) ||\n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) ||\n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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);"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$i(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0;let s,r;const o=[];if(o.push("// Instancing edges 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"),o.push("uniform vec4 color;"),i)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),s=0,r=t.sectionPlanes.length;s 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,r=t.sectionPlanes.length;s 0.0) { discard; }"),o.push("}")}return o.push("gl_FragColor = color;"),o.push("}"),o}const tempVec3a$l=math.vec3();class InstancingEdgesRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingEdgesShaderSource(this._scene),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.canvas.gl,a=t._state,n=this._instanceExt,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let h,c=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),c=!0),o.uniformMatrix4fv(this._uViewMatrix,!1,l?createRTCViewMat(s.viewMatrix,l):s.viewMatrix),l?e.lastRTCCenter&&math.compareVec3(l,e.lastRTCCenter)||(e.lastRTCCenter=l,c=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,c=!0),c){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,n=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry picking vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 pickColor;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vPickColor;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool pickable = (float(flags2.z) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("if ( culled || (!pickInvisible && !visible) || !pickable) {"),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);"),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(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$j(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push("}")}return s.push("gl_FragColor = vPickColor; "),s.push("}"),s}const tempVec3a$m=math.vec3();class InstancingPickMeshRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickMeshShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e),l=!0);const h=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,c=n?createRTCViewMat(h,n):h;if(r.uniformMatrix4fv(this._uViewMatrix,!1,c),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(o.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(o.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(o.modelMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPickColor.bindArrayBuffer(o.pickColorsBuf),a.vertexAttribDivisorANGLE(this._aPickColor.location,1),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aFlags.bindArrayBuffer(o.flagsBuf),a.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(o.flags2Buf),a.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(o.offsetsBuf),a.vertexAttribDivisorANGLE(this._aOffset.location,1)),o.indicesBuf.bind(),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool pickable = (float(flags2.z) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("if (culled || (!pickInvisible && !visible) || !pickable) {"),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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$k(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),s.push("uniform float zNear;"),s.push("uniform float zFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" float zNormalizedDepth = abs((zNear + vViewPosition.z) / (zFar - zNear));"),s.push(" gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}const tempVec3a$n=math.vec3();class InstancingPickDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0);const h=s.camera.project._state;r.uniform1i(this._uPickInvisible,e.pickInvisible);const c=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,d=n?createRTCViewMat(c,n):c;if(r.uniformMatrix4fv(this._uViewMatrix,!1,d),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.uniform1f(this._uZNear,h.near),r.uniform1f(this._uZFar,h.far),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry normals vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec2 normal;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("attribute vec4 modelNormalMatrixCol0;"),i.push("attribute vec4 modelNormalMatrixCol1;"),i.push("attribute vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool pickable = (float(flags2.z) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || (!pickInvisible && !visible) || !pickable) {"),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);"),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(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$l(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}const tempVec3a$o=math.vec3();class InstancingPickNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniform1i(this._uPickInvisible,e.pickInvisible);const h=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,c=n?createRTCViewMat(h,n):h;if(r.uniformMatrix4fv(this._uViewMatrix,!1,c),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing occlusion vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("if (culled || !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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$m(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}const tempVec3a$p=math.vec3();class InstancingOcclusionRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingOcclusionShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,n?createRTCViewMat(i.viewMatrix,n):i.viewMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry depth drawing vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("if ( culled || !visible || transparent || xrayed) {"),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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$n(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Instancing geometry depth 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i 0.0) { discard; }"),o.push("}")}return o.push(" gl_FragColor = packDepthToRGBA( gl_FragCoord.z); "),o.push("}"),o}const tempVec3a$q=math.vec3();class InstancingDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,n?createRTCViewMat(i.viewMatrix,n):i.viewMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry depth drawing vertex shader"),i.push("attribute vec3 position;"),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("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (culled || !visible || transparent || xrayed) {"),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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = 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(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$o(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}const tempVec3a$r=math.vec3(),tempMat4a$2=math.mat4();class InstancingNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,n?createRTCViewMat(i.viewMatrix,n):i.viewMatrix),r.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry shadow drawing vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$p(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Instancing geometry shadow 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i 0.0) { discard; }"),o.push("}")}return o.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),o.push("}"),o}const tempVec3a$s=math.vec3();class InstancingShadowRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._lastLightId=null,this._shaderSource=new InstancingShadowShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,t)),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(o.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(o.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(o.modelMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(o.offsetsBuf),a.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aColor.bindArrayBuffer(o.colorsBuf),a.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(o.flagsBuf),a.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(o.flags2Buf),a.vertexAttribDivisorANGLE(this._aFlags2.location,1));const n=s._sectionPlanesState.sectionPlanes.length;if(n>0){const e=s._sectionPlanesState.sectionPlanes,o=t.layerIndex*n,a=i.renderFlags,l=t._state.rtcCenter;for(let t=0;t{i._compile()}),e.on("destroyed",()=>{delete sceneInstancingRenderers[t],i._destroy()})),i}const bigIndicesSupported$2=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,MAX_VERTS$1=bigIndicesSupported$2?5e6:65530,quantizedPositions=new Uint16Array(3*MAX_VERTS$1),compressedNormals=new Int8Array(3*MAX_VERTS$1),tempUint8Vec4=new Uint8Array(4),tempVec3a$t=math.vec3(),tempVec4a$1=math.vec4([0,0,0,1]),tempVec4b$1=math.vec4([0,0,0,1]),tempVec4c$1=math.vec4([0,0,0,1]);class InstancingLayer{constructor(e,t){this.layerIndex=t.layerIndex,this._instancingRenderers=getInstancingRenderers(e.scene),this.model=e,this._aabb=math.collapseAABB3();let i,s=t.primitive||"triangles";const r=e.scene.canvas.gl;switch(s){case"points":i=r.POINTS;break;case"lines":i=r.LINES;break;case"line-loop":i=r.LINE_LOOP;break;case"line-strip":i=r.LINE_STRIP;break;case"triangles":i=r.TRIANGLES;break;case"triangle-strip":i=r.TRIANGLE_STRIP;break;case"triangle-fan":i=r.TRIANGLE_FAN;break;default:e.error(`Unsupported value for 'primitive': '${s}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),i=r.TRIANGLES,s="triangles"}const o={primitiveName:s,primitive:i,positionsDecodeMatrix:math.mat4(),numInstances:0,obb:math.OBB3(),rtcCenter:null},a=!!t.positionsDecodeMatrix;if(t.positions)if(a){let e=!1;o.positionsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,t.positions,t.positions.length,3,r.STATIC_DRAW,e),o.positionsDecodeMatrix.set(t.positionsDecodeMatrix);let i=math.collapseAABB3();math.expandAABB3Points3(i,t.positions),geometryCompressionUtils.decompressAABB(i,o.positionsDecodeMatrix),math.AABB3ToOBB3(i,o.obb)}else{let e=t.positions.length,i=math.collapseAABB3();math.expandAABB3Points3(i,t.positions),math.AABB3ToOBB3(i,o.obb),quantizePositions$1(t.positions,e,i,quantizedPositions,o.positionsDecodeMatrix);let s=!1;o.positionsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,quantizedPositions,e,3,r.STATIC_DRAW,s)}if(t.normals)if(a){const e=!0;o.normalsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,t.normals,t.normals.length,3,r.STATIC_DRAW,e)}else{const e=octEncodeNormals(t.normals,t.normals.length,compressedNormals,0),i=!0;o.normalsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,compressedNormals,e,3,r.STATIC_DRAW,i)}t.indices&&(o.indicesBuf=new ArrayBuf(r,r.ELEMENT_ARRAY_BUFFER,bigIndicesSupported$2?new Uint32Array(t.indices):new Uint16Array(t.indices),t.indices.length,1,r.STATIC_DRAW));let n=t.edgeIndices;n||(n=buildEdgeIndices(t.positions,t.indices,null,t.edgeThreshold||10)),o.edgeIndicesBuf=new ArrayBuf(r,r.ELEMENT_ARRAY_BUFFER,bigIndicesSupported$2?new Uint32Array(n):new Uint16Array(n),n.length,1,r.STATIC_DRAW),this._state=new RenderState(o),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=t.indices?t.indices.length/3:0,this._flags=[],this._flags2=[],this._colors=[],this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],t.rtcCenter&&(this._state.rtcCenter=math.vec3(t.rtcCenter)),this._finalized=!1,this.aabb=math.collapseAABB3()}createPortion(e,t,i,s,r,o,a){if(this._finalized)throw"Already finalized";const n=e&RENDER_FLAGS.VISIBLE?255:0,l=e&RENDER_FLAGS.XRAYED?255:0,h=e&RENDER_FLAGS.HIGHLIGHTED?255:0,c=e&RENDER_FLAGS.HIGHLIGHTED?255:0,d=e&RENDER_FLAGS.CLIPPABLE?255:0,u=e&RENDER_FLAGS.EDGES?255:0,p=e&RENDER_FLAGS.PICKABLE?255:0,m=e&RENDER_FLAGS.CULLED?255:0;this._flags.push(n),this._flags.push(l),this._flags.push(h),this._flags.push(c),this._flags2.push(d),this._flags2.push(u),this._flags2.push(p),this._flags2.push(m),n&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),l&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),h&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),c&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),d&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),u&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),p&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),m&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++);const _=t[0],f=t[1],g=t[2];t[3];i<255&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._colors.push(_),this._colors.push(f),this._colors.push(g),this._colors.push(i),this._offsets.push(0),this._offsets.push(0),this._offsets.push(0),this._modelMatrixCol0.push(s[0]),this._modelMatrixCol0.push(s[4]),this._modelMatrixCol0.push(s[8]),this._modelMatrixCol0.push(s[12]),this._modelMatrixCol1.push(s[1]),this._modelMatrixCol1.push(s[5]),this._modelMatrixCol1.push(s[9]),this._modelMatrixCol1.push(s[13]),this._modelMatrixCol2.push(s[2]),this._modelMatrixCol2.push(s[6]),this._modelMatrixCol2.push(s[10]),this._modelMatrixCol2.push(s[14]);let v=math.transposeMat4(s,math.mat4()),b=math.inverseMat4(v);this._modelNormalMatrixCol0.push(b[0]),this._modelNormalMatrixCol0.push(b[4]),this._modelNormalMatrixCol0.push(b[8]),this._modelNormalMatrixCol0.push(b[12]),this._modelNormalMatrixCol1.push(b[1]),this._modelNormalMatrixCol1.push(b[5]),this._modelNormalMatrixCol1.push(b[9]),this._modelNormalMatrixCol1.push(b[13]),this._modelNormalMatrixCol2.push(b[2]),this._modelNormalMatrixCol2.push(b[6]),this._modelNormalMatrixCol2.push(b[10]),this._modelNormalMatrixCol2.push(b[14]),this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]),math.collapseAABB3(o);const y=this._state.obb,M=y.length;for(let e=0;e0){const t=!1;this._state.colorsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(this._flags.length>0){const t=!0;this._state.flagsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._flags),this._flags.length,4,e.DYNAMIC_DRAW,t),this._state.flags2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._flags2),this._flags2.length,4,e.DYNAMIC_DRAW,t),this._flags=[],this._flags2=[]}if(this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._state.modelNormalMatrixCol0Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelNormalMatrixCol1Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelNormalMatrixCol2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;this._state.pickColorsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._finalized=!0}initFlags(e,t){t&RENDER_FLAGS.VISIBLE&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&RENDER_FLAGS.HIGHLIGHTED&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&RENDER_FLAGS.XRAYED&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&RENDER_FLAGS.SELECTED&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&RENDER_FLAGS.CLIPPABLE&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&RENDER_FLAGS.EDGES&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&RENDER_FLAGS.PICKABLE&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&RENDER_FLAGS.CULLED&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),this._setFlags(e,t),this._setFlags2(e,t)}setVisible(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.VISIBLE?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t)}setHighlighted(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.HIGHLIGHTED?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t)}setXRayed(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.XRAYED?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t)}setSelected(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.SELECTED?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t)}setEdges(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.EDGES?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags2(e,t)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.CLIPPABLE?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.PICKABLE?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t)}setCulled(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.CULLED?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags2(e,t)}setColor(e,t,i=!1){if(!this._finalized)throw"Not finalized";if(tempUint8Vec4[0]=t[0],tempUint8Vec4[1]=t[1],tempUint8Vec4[2]=t[2],tempUint8Vec4[3]=t[3],i){t[3]<255?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--)}this._state.colorsBuf.setData(tempUint8Vec4,4*e,4)}_setFlags(e,t){if(!this._finalized)throw"Not finalized";const i=t&RENDER_FLAGS.VISIBLE?255:0,s=t&RENDER_FLAGS.XRAYED?255:0,r=t&RENDER_FLAGS.HIGHLIGHTED?255:0,o=t&RENDER_FLAGS.SELECTED?255:0;tempUint8Vec4[0]=i,tempUint8Vec4[1]=s,tempUint8Vec4[2]=r,tempUint8Vec4[3]=o,this._state.flagsBuf.setData(tempUint8Vec4,4*e,4)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";const i=t&RENDER_FLAGS.CLIPPABLE?255:0,s=t&RENDER_FLAGS.EDGES?255:0,r=t&RENDER_FLAGS.PICKABLE?255:0,o=t&RENDER_FLAGS.CULLED?255:0;tempUint8Vec4[0]=i,tempUint8Vec4[1]=s,tempUint8Vec4[2]=r,tempUint8Vec4[3]=o,this._state.flags2Buf.setData(tempUint8Vec4,4*e,4)}setOffset(e,t){if(!this._finalized)throw"Not finalized";tempVec3a$t[0]=t[0],tempVec3a$t[1]=t[1],tempVec3a$t[2]=t[2],this._state.offsetsBuf.setData(tempVec3a$t,3*e,3)}drawNormalFillOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(e.withSAO?this._instancingRenderers.drawRendererWithSAO&&this._instancingRenderers.drawRendererWithSAO.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE):this._instancingRenderers.drawRenderer&&this._instancingRenderers.drawRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE))}drawNormalEdgesOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE)}drawNormalFillTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.drawRenderer&&this._instancingRenderers.drawRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_TRANSPARENT)}drawNormalTransparentEdges(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_TRANSPARENT)}drawDepth(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(e,this)}drawNormals(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(e,this)}drawXRayedFillOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedEdgesOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedFillTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedEdgesTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawHighlightedFillOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedEdgesOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedFillTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedEdgesTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawSelectedFillOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedEdgesOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedFillTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedEdgesTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawPickMesh(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(e,this)}drawPickDepths(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(e,this)}drawPickNormals(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickNormalsRenderer&&this._instancingRenderers.pickNormalsRenderer.drawLayer(e,this)}drawOcclusion(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(e,this)}drawShadow(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(e,this)}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=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.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const quantizePositions$1=function(){const e=math.mat4(),t=math.mat4(),i=math.vec3();return function(s,r,o,a,n){const l=o[0],h=o[1],c=o[2],d=o[3],u=o[4],p=o[5],m=o[3]-l,_=o[4]-h,f=o[5]-c,g=d!==l?65535/(d-l):0,v=u!==h?65535/(u-h):0,b=p!==c?65535/(p-c):0;for(let e=0;el&&(a=r,l=n),(n=dot$2(e,h,o=octDecodeVec2$2(r=octEncodeVec3$2(e,h,"floor","ceil"))))>l&&(a=r,l=n),(n=dot$2(e,h,o=octDecodeVec2$2(r=octEncodeVec3$2(e,h,"ceil","ceil"))))>l&&(a=r,l=n),i[s+h+0]=a[0],i[s+h+1]=a[1],i[s+h+2]=0;return s+=t}function octEncodeVec3$2(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=r,t=o;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 octDecodeVec2$2(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 dot$2(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const instancedArraysSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.ANGLE_instanced_arrays,tempMat4$1=math.mat4(),defaultScale=math.vec3([1,1,1]),defaultPosition=math.vec3([0,0,0]),defaultRotation=math.vec3([0,0,0]),defaultQuaternion=math.identityQuaternion();class PerformanceModel extends Component{constructor(e,t={}){super(e,t),this._aabb=math.collapseAABB3(),this._aabbDirty=!1,this._layerList=[],this._nodeList=[],this._lastDecodeMatrix=null,this._instancingLayers={},this._currentBatchingLayer=null,this._batchingScratchMemory=getBatchingLayerScratchMemory(this),this._meshes={},this._nodes={},this.renderFlags=new RenderFlags,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._edgeThreshold=t.edgeThreshold||10,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,this._position=new Float32Array(t.position||[0,0,0]),this._rotation=new Float32Array(t.rotation||[0,0,0]),this._quaternion=new Float32Array(t.quaternion||[0,0,0,1]),t.rotation&&math.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=new Float32Array(t.scale||[1,1,1]),this._worldMatrix=math.mat4(),math.composeMat4(this._position,this._quaternion,this._scale,this._worldMatrix),this._worldNormalMatrix=math.mat4(),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=math.mat4(),this._viewNormalMatrix=math.mat4(),this._viewMatrixDirty=!0,this._worldMatrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",()=>{this._viewMatrixDirty=!0})}get isPerformanceModel(){return!0}get position(){return this._position}get rotation(){return this._rotation}get quaternion(){return this._quaternion}get scale(){return this._scale}get matrix(){return this._worldMatrix}get worldMatrix(){return this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrix}get viewMatrix(){return this._viewMatrix?(this._viewMatrixDirty&&(math.mulMat4(this.scene.camera.viewMatrix,this._worldMatrix,this._viewMatrix),math.inverseMat4(this._viewMatrix,this._viewNormalMatrix),math.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewMatrix):this.scene.camera.viewMatrix}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}get viewNormalMatrix(){return this._viewNormalMatrix?(this._viewMatrixDirty&&(math.mulMat4(this.scene.camera.viewMatrix,this._worldMatrix,this._viewMatrix),math.inverseMat4(this._viewMatrix,this._viewNormalMatrix),math.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}createGeometry(e){if(!instancedArraysSupported)return void this.error("WebGL instanced arrays not supported");const t=e.id;if(void 0===t||null===t)return void this.error("Config missing: id");if(this._instancingLayers[t])return void this.error("Geometry already created: "+t);const i=new InstancingLayer(this,utils.apply({layerIndex:0,edgeThreshold:this._edgeThreshold},e));this._instancingLayers[t]=i,this._layerList.push(i),this.numGeometries++,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0}createMesh(e){let t=e.id;if(void 0===t||null===t)return void this.error("Config missing: id");if(this._meshes[t])return void this.error("PerformanceModel already has a Mesh with this ID: "+t);const i=e.geometryId,s=void 0!==i;if(s){if(!instancedArraysSupported)return void this.error("WebGL instanced arrays not supported");if(!this._instancingLayers[i])return void this.error("Geometry not found: "+i+" - ensure that you create it first with createGeometry()")}let r,o;const a=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],n=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;n<255&&this.numTransparentLayerPortions++;const l=new PerformanceMesh(this,t,a,n),h=l.pickId,c=new Uint8Array([255&h,h>>8&255,h>>16&255,h>>24&255]),d=math.collapseAABB3();if(s){let t,s=this._worldMatrixNonIdentity?this._worldMatrix:null;if(e.matrix)t=e.matrix;else{const i=e.scale||defaultScale,s=e.position||defaultPosition,r=e.rotation||defaultRotation;math.eulerToQuaternion(r,"XYZ",defaultQuaternion),t=math.composeMat4(s,defaultQuaternion,i,tempMat4$1)}const h=this._instancingLayers[i];r=h,o=h.createPortion(0,a,n,t,s,d,c),math.expandAABB3(this._aabb,d);const u=Math.round(h.numIndices/3);this._numTriangles+=u,l.numTriangles=u,l.rtcCenter=h.rtcCenter}else{let t=e.primitive||"triangles";"points"!==t&&"lines"!==t&&"line-loop"!==t&&"line-strip"!==t&&"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t&&(this.error(`Unsupported value for 'primitive': '${t}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),t="triangles");let i=e.indices,s=e.edgeIndices,h=e.positions;if(!h)return this.error("Config missing: positions (no meshIds provided, so expecting geometry arrays instead)"),null;let u=e.normals;if(!u)return this.error("Config missing: normals (no meshIds provided, so expecting geometry arrays instead)"),null;if(!s&&!i)return this.error("Config missing: must have one or both of indices and edgeIndices (no meshIds provided, so expecting geometry arrays instead)"),null;let p,m=!1;e.rtcCenter&&(this._lastRTCCenter?math.compareVec3(this._lastRTCCenter,e.rtcCenter)||(m=!0,this._lastRTCCenter.set(e.rtcCenter)):(m=!0,this._lastRTCCenter=math.vec3(e.rtcCenter))),e.positionsDecodeMatrix&&(this._lastDecodeMatrix?math.compareMat4(this._lastDecodeMatrix,e.positionsDecodeMatrix)||(m=!0,this._lastDecodeMatrix.set(e.positionsDecodeMatrix)):(m=!0,this._lastDecodeMatrix=math.mat4(e.positionsDecodeMatrix))),m&&this._currentBatchingLayer&&(this._currentBatchingLayer.finalize(),this._currentBatchingLayer=null),this._currentBatchingLayer&&(this._currentBatchingLayer.canCreatePortion(h.length,i.length)||(this._currentBatchingLayer.finalize(),this._currentBatchingLayer=null)),this._currentBatchingLayer||(this._currentBatchingLayer=new BatchingLayer(this,{layerIndex:0,primitive:"triangles",scratchMemory:this._batchingScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,rtcCenter:e.rtcCenter}),this._layerList.push(this._currentBatchingLayer)),r=this._currentBatchingLayer,!s&&i&&(s=buildEdgeIndices(h,i,null,this._edgeThreshold));let _=this._worldMatrixNonIdentity?this._worldMatrix:null;if(!e.positionsDecodeMatrix)if(e.matrix)p=e.matrix;else{const t=e.scale||defaultScale,i=e.position||defaultPosition,s=e.rotation||defaultRotation;math.eulerToQuaternion(s,"XYZ",defaultQuaternion),p=math.composeMat4(i,defaultQuaternion,t,tempMat4$1)}o=this._currentBatchingLayer.createPortion(h,u,i,s,0,a,n,p,_,d,c),math.expandAABB3(this._aabb,d),this.numGeometries++;const f=Math.round(i.length/3);this._numTriangles+=f,l.numTriangles=f,l.rtcCenter=e.rtcCenter}l.parent=null,l._layer=r,l._portionId=o,l.aabb=d,this._meshes[t]=l}createEntity(e){let t=e.id;void 0===t?t=math.createUUID():this.scene.components[t]&&(this.error("Scene already has a Component with this ID: "+t+" - will assign random ID"),t=math.createUUID());const i=e.meshIds;if(void 0===i)return void this.error("Config missing: meshIds");let s,r,o,a,n=[];for(s=0,r=i.length;s0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._nodeList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._nodeList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._nodeList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._nodeList.length;t0}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._nodeList.length;t0}set colorize(e){this._colorize=e;for(let t=0,i=this._nodeList.length;t0&&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;t0)for(let o=0;o0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedFillTransparent=!0:e.xrayedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){const t=this.scene.edgeMaterial._state;t.edges&&(t.alpha<1?e.normalEdgesTransparent=!0:e.normalEdgesOpaque=!0)}if(this.numTransparentLayerPortions>0&&(e.normalFillTransparent=!0),this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedFillTransparent=!0:e.selectedFillOpaque=!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.highlightedFillTransparent=!0:e.highlightedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}drawNormalFillOpaque(e){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i{t(e)},function(e){i(e)})}getXKT(e,t,i){var s=()=>{};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),s=new Uint8Array(e);for(var a=0;a0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new n,this.strm.avail_out=0;var i=s.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==h)throw new Error(a[i]);if(t.header&&s.deflateSetHeader(this.strm,t.header),t.dictionary){var m;if(m="string"==typeof t.dictionary?o.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=s.deflateSetDictionary(this.strm,m))!==h)throw new Error(a[i]);this._dict_set=!0}}function m(e,t){var i=new p(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}p.prototype.push=function(e,t){var i,a,n=this.strm,c=this.options.chunkSize;if(this.ended)return!1;a=t===~~t?t:!0===t?4:0,"string"==typeof e?n.input=o.string2buf(e):"[object ArrayBuffer]"===l.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;do{if(0===n.avail_out&&(n.output=new r.Buf8(c),n.next_out=0,n.avail_out=c),1!==(i=s.deflate(n,a))&&i!==h)return this.onEnd(i),this.ended=!0,!1;0!==n.avail_out&&(0!==n.avail_in||4!==a&&2!==a)||("string"===this.options.to?this.onData(o.buf2binstring(r.shrinkBuf(n.output,n.next_out))):this.onData(r.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||0===n.avail_out)&&1!==i);return 4===a?(i=s.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===h):2!==a||(this.onEnd(h),n.avail_out=0,!0)},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===h&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=p,i.deflate=m,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,m(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,m(e,t)}},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(e,t,i){var s=e("./zlib/inflate"),r=e("./utils/common"),o=e("./utils/strings"),a=e("./zlib/constants"),n=e("./zlib/messages"),l=e("./zlib/zstream"),h=e("./zlib/gzheader"),c=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=r.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=s.inflateInit2(this.strm,t.windowBits);if(i!==a.Z_OK)throw new Error(n[i]);if(this.header=new h,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===c.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=s.inflateSetDictionary(this.strm,t.dictionary))!==a.Z_OK))throw new Error(n[i])}function u(e,t){var i=new d(t);if(i.push(e,!0),i.err)throw i.msg||n[i.err];return i.result}d.prototype.push=function(e,t){var i,n,l,h,d,u=this.strm,p=this.options.chunkSize,m=this.options.dictionary,_=!1;if(this.ended)return!1;n=t===~~t?t:!0===t?a.Z_FINISH:a.Z_NO_FLUSH,"string"==typeof e?u.input=o.binstring2buf(e):"[object ArrayBuffer]"===c.call(e)?u.input=new Uint8Array(e):u.input=e,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new r.Buf8(p),u.next_out=0,u.avail_out=p),(i=s.inflate(u,a.Z_NO_FLUSH))===a.Z_NEED_DICT&&m&&(i=s.inflateSetDictionary(this.strm,m)),i===a.Z_BUF_ERROR&&!0===_&&(i=a.Z_OK,_=!1),i!==a.Z_STREAM_END&&i!==a.Z_OK)return this.onEnd(i),this.ended=!0,!1;u.next_out&&(0!==u.avail_out&&i!==a.Z_STREAM_END&&(0!==u.avail_in||n!==a.Z_FINISH&&n!==a.Z_SYNC_FLUSH)||("string"===this.options.to?(l=o.utf8border(u.output,u.next_out),h=u.next_out-l,d=o.buf2string(u.output,l),u.next_out=h,u.avail_out=p-h,h&&r.arraySet(u.output,u.output,l,h,0),this.onData(d)):this.onData(r.shrinkBuf(u.output,u.next_out)))),0===u.avail_in&&0===u.avail_out&&(_=!0)}while((u.avail_in>0||0===u.avail_out)&&i!==a.Z_STREAM_END);return i===a.Z_STREAM_END&&(n=a.Z_FINISH),n===a.Z_FINISH?(i=s.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===a.Z_OK):n!==a.Z_SYNC_FLUSH||(this.onEnd(a.Z_OK),u.avail_out=0,!0)},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===a.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=d,i.inflate=u,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,u(e,t)},i.ungzip=u},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(e,t,i){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var s in i)r(i,s)&&(e[s]=i[s])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var o={arraySet:function(e,t,i,s,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+s),r);else for(var o=0;o=252?6:n>=248?5:n>=240?4:n>=224?3:n>=192?2:1;function l(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&r))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var i="",a=0;a>>6,t[a++]=128|63&i):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|63&i):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new s.Buf8(e.length),i=0,r=t.length;i4)h[s++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&i1?h[s++]=65533:r<65536?h[s++]=r:(r-=65536,h[s++]=55296|r>>10&1023,h[s++]=56320|1023&r)}return l(h,s)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0?t:0===i?t:i+a[e[i]]>t?i:t}},{"./common":3}],5:[function(e,t,i){t.exports=function(e,t,i,s){for(var r=65535&e|0,o=e>>>16&65535|0,a=0;0!==i;){i-=a=i>2e3?2e3:i;do{o=o+(r=r+t[s++]|0)|0}while(--a);r%=65521,o%=65521}return r|o<<16|0}},{}],6:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],7:[function(e,t,i){var s=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,r){var o=s,a=r+i;e^=-1;for(var n=r;n>>8^o[255&(e^t[n])];return-1^e}},{}],8:[function(e,t,i){var s,r=e("../utils/common"),o=e("./trees"),a=e("./adler32"),n=e("./crc32"),l=e("./messages"),h=0,c=1,d=3,u=4,p=5,m=0,_=1,f=-2,g=-3,v=-5,b=-1,y=1,M=2,w=3,P=4,x=0,E=2,A=8,C=9,R=15,S=8,L=286,D=30,T=19,k=2*L+1,B=15,I=3,F=258,N=F+I+1,V=32,O=42,j=69,U=73,G=91,z=103,H=113,$=666,W=1,X=2,Y=3,q=4,K=3;function Z(e,t){return e.msg=l[t],t}function Q(e){return(e<<1)-(e>4?9:0)}function J(e){for(var t=e.length;--t>=0;)e[t]=0}function ee(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(r.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function te(e,t){o._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ee(e.strm)}function ie(e,t){e.pending_buf[e.pending++]=t}function se(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function re(e,t){var i,s,r=e.max_chain_length,o=e.strstart,a=e.prev_length,n=e.nice_match,l=e.strstart>e.w_size-N?e.strstart-(e.w_size-N):0,h=e.window,c=e.w_mask,d=e.prev,u=e.strstart+F,p=h[o+a-1],m=h[o+a];e.prev_length>=e.good_match&&(r>>=2),n>e.lookahead&&(n=e.lookahead);do{if(h[(i=t)+a]===m&&h[i+a-1]===p&&h[i]===h[o]&&h[++i]===h[o+1]){o+=2,i++;do{}while(h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&oa){if(e.match_start=t,a=s,s>=n)break;p=h[o+a-1],m=h[o+a]}}}while((t=d[t&c])>l&&0!=--r);return a<=e.lookahead?a:e.lookahead}function oe(e){var t,i,s,o,l,h,c,d,u,p,m=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=m+(m-N)){r.arraySet(e.window,e.window,m,m,0),e.match_start-=m,e.strstart-=m,e.block_start-=m,t=i=e.hash_size;do{s=e.head[--t],e.head[t]=s>=m?s-m:0}while(--i);t=i=m;do{s=e.prev[--t],e.prev[t]=s>=m?s-m:0}while(--i);o+=m}if(0===e.strm.avail_in)break;if(h=e.strm,c=e.window,d=e.strstart+e.lookahead,u=o,p=void 0,(p=h.avail_in)>u&&(p=u),i=0===p?0:(h.avail_in-=p,r.arraySet(c,h.input,h.next_in,p,d),1===h.state.wrap?h.adler=a(h.adler,c,p,d):2===h.state.wrap&&(h.adler=n(h.adler,c,p,d)),h.next_in+=p,h.total_in+=p,p),e.lookahead+=i,e.lookahead+e.insert>=I)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<=I&&(e.ins_h=(e.ins_h<=I)if(s=o._tr_tally(e,e.strstart-e.match_start,e.match_length-I),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=I){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=I&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=I-1)),e.prev_length>=I&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-I,s=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-I),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=(e.ins_h<15&&(n=2,s-=16),o<1||o>C||i!==A||s<8||s>15||t<0||t>9||a<0||a>P)return Z(e,f);8===s&&(s=9);var l=new function(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=A,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new r.Buf16(2*k),this.dyn_dtree=new r.Buf16(2*(2*D+1)),this.bl_tree=new r.Buf16(2*(2*T+1)),J(this.dyn_ltree),J(this.dyn_dtree),J(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new r.Buf16(B+1),this.heap=new r.Buf16(2*L+1),J(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(2*L+1),J(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0};return e.state=l,l.strm=e,l.wrap=n,l.gzhead=null,l.w_bits=s,l.w_size=1<e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(oe(e),0===e.lookahead&&t===h)return W;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var s=e.block_start+i;if((0===e.strstart||e.strstart>=s)&&(e.lookahead=e.strstart-s,e.strstart=s,te(e,!1),0===e.strm.avail_out))return W;if(e.strstart-e.block_start>=e.w_size-N&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):(e.strstart>e.block_start&&(te(e,!1),e.strm.avail_out),W)}),new le(4,4,8,4,ae),new le(4,5,16,8,ae),new le(4,6,32,32,ae),new le(4,4,16,16,ne),new le(8,16,32,32,ne),new le(8,16,128,128,ne),new le(8,32,128,256,ne),new le(32,128,258,1024,ne),new le(32,258,258,4096,ne)],i.deflateInit=function(e,t){return de(e,t,A,R,S,x)},i.deflateInit2=de,i.deflateReset=ce,i.deflateResetKeep=he,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?f:(e.state.gzhead=t,m):f},i.deflate=function(e,t){var i,r,a,l;if(!e||!e.state||t>p||t<0)return e?Z(e,f):f;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||r.status===$&&t!==u)return Z(e,0===e.avail_out?v:f);if(r.strm=e,i=r.last_flush,r.last_flush=t,r.status===O)if(2===r.wrap)e.adler=0,ie(r,31),ie(r,139),ie(r,8),r.gzhead?(ie(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),ie(r,255&r.gzhead.time),ie(r,r.gzhead.time>>8&255),ie(r,r.gzhead.time>>16&255),ie(r,r.gzhead.time>>24&255),ie(r,9===r.level?2:r.strategy>=M||r.level<2?4:0),ie(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(ie(r,255&r.gzhead.extra.length),ie(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=n(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=j):(ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,9===r.level?2:r.strategy>=M||r.level<2?4:0),ie(r,K),r.status=H);else{var g=A+(r.w_bits-8<<4)<<8;g|=(r.strategy>=M||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(g|=V),g+=31-g%31,r.status=H,se(r,g),0!==r.strstart&&(se(r,e.adler>>>16),se(r,65535&e.adler)),e.adler=1}if(r.status===j)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending!==r.pending_buf_size));)ie(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=U)}else r.status=U;if(r.status===U)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindexa&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.gzindex=0,r.status=G)}else r.status=G;if(r.status===G)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindexa&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.status=z)}else r.status=z;if(r.status===z&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&ee(e),r.pending+2<=r.pending_buf_size&&(ie(r,255&e.adler),ie(r,e.adler>>8&255),e.adler=0,r.status=H)):r.status=H),0!==r.pending){if(ee(e),0===e.avail_out)return r.last_flush=-1,m}else if(0===e.avail_in&&Q(t)<=Q(i)&&t!==u)return Z(e,v);if(r.status===$&&0!==e.avail_in)return Z(e,v);if(0!==e.avail_in||0!==r.lookahead||t!==h&&r.status!==$){var b=r.strategy===M?function(e,t){for(var i;;){if(0===e.lookahead&&(oe(e),0===e.lookahead)){if(t===h)return W;break}if(e.match_length=0,i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?W:X}(r,t):r.strategy===w?function(e,t){for(var i,s,r,a,n=e.window;;){if(e.lookahead<=F){if(oe(e),e.lookahead<=F&&t===h)return W;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=I&&e.strstart>0&&(s=n[r=e.strstart-1])===n[++r]&&s===n[++r]&&s===n[++r]){a=e.strstart+F;do{}while(s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=I?(i=o._tr_tally(e,1,e.match_length-I),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?W:X}(r,t):s[r.level].func(r,t);if(b!==Y&&b!==q||(r.status=$),b===W||b===Y)return 0===e.avail_out&&(r.last_flush=-1),m;if(b===X&&(t===c?o._tr_align(r):t!==p&&(o._tr_stored_block(r,0,0,!1),t===d&&(J(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),ee(e),0===e.avail_out))return r.last_flush=-1,m}return t!==u?m:r.wrap<=0?_:(2===r.wrap?(ie(r,255&e.adler),ie(r,e.adler>>8&255),ie(r,e.adler>>16&255),ie(r,e.adler>>24&255),ie(r,255&e.total_in),ie(r,e.total_in>>8&255),ie(r,e.total_in>>16&255),ie(r,e.total_in>>24&255)):(se(r,e.adler>>>16),se(r,65535&e.adler)),ee(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?m:_)},i.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==O&&t!==j&&t!==U&&t!==G&&t!==z&&t!==H&&t!==$?Z(e,f):(e.state=null,t===H?Z(e,g):m):f},i.deflateSetDictionary=function(e,t){var i,s,o,n,l,h,c,d,u=t.length;if(!e||!e.state)return f;if(2===(n=(i=e.state).wrap)||1===n&&i.status!==O||i.lookahead)return f;for(1===n&&(e.adler=a(e.adler,t,u,0)),i.wrap=0,u>=i.w_size&&(0===n&&(J(i.head),i.strstart=0,i.block_start=0,i.insert=0),d=new r.Buf8(i.w_size),r.arraySet(d,t,u-i.w_size,i.w_size,0),t=d,u=i.w_size),l=e.avail_in,h=e.next_in,c=e.input,e.avail_in=u,e.next_in=0,e.input=t,oe(i);i.lookahead>=I;){s=i.strstart,o=i.lookahead-(I-1);do{i.ins_h=(i.ins_h<>>=y=b>>>24,m-=y,0===(y=b>>>16&255))A[o++]=65535&b;else{if(!(16&y)){if(0==(64&y)){b=_[(65535&b)+(p&(1<>>=y,m-=y),m<15&&(p+=E[s++]<>>=y=b>>>24,m-=y,!(16&(y=b>>>16&255))){if(0==(64&y)){b=f[(65535&b)+(p&(1<l){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=y,m-=y,w>(y=o-a)){if((y=w-y)>c&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(P=0,x=u,0===d){if(P+=h-y,y2;)A[o++]=x[P++],A[o++]=x[P++],A[o++]=x[P++],M-=3;M&&(A[o++]=x[P++],M>1&&(A[o++]=x[P++]))}else{P=o-w;do{A[o++]=A[P++],A[o++]=A[P++],A[o++]=A[P++],M-=3}while(M>2);M&&(A[o++]=A[P++],M>1&&(A[o++]=A[P++]))}break}}break}}while(s>3,p&=(1<<(m-=M<<3))-1,e.next_in=s,e.next_out=o,e.avail_in=s>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function re(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=w,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(ee),t.distcode=t.distdyn=new s.Buf32(te),t.sane=1,t.back=-1,m):g}function oe(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,re(e)):g}function ae(e,t){var i,s;return e&&e.state?(s=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?g:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,oe(e))):g}function ne(e,t){var i,r;return e?(r=new function(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0},e.state=r,r.window=null,(i=ae(e,t))!==m&&(e.state=null),i):g}var le,he,ce=!0;function de(e){if(ce){var t;for(le=new s.Buf32(512),he=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(n(h,e.lens,0,288,le,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;n(c,e.lens,0,32,he,0,e.work,{bits:5}),ce=!1}e.lencode=le,e.lenbits=9,e.distcode=he,e.distbits=5}function ue(e,t,i,r){var o,a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(s.arraySet(a.window,t,i-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((o=a.wsize-a.wnext)>r&&(o=r),s.arraySet(a.window,t,i-r,o,a.wnext),(r-=o)?(s.arraySet(a.window,t,i-r,r,0),a.wnext=r,a.whave=a.wsize):(a.wnext+=o,a.wnext===a.wsize&&(a.wnext=0),a.whave>>8&255,i.check=o(i.check,Ce,2,0),ne=0,le=0,i.mode=P;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&ne)<<8)+(ne>>8))%31){e.msg="incorrect header check",i.mode=Z;break}if((15&ne)!==M){e.msg="unknown compression method",i.mode=Z;break}if(le-=4,we=8+(15&(ne>>>=4)),0===i.wbits)i.wbits=we;else if(we>i.wbits){e.msg="invalid window size",i.mode=Z;break}i.dmax=1<>8&1),512&i.flags&&(Ce[0]=255&ne,Ce[1]=ne>>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0,i.mode=x;case x:for(;le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>8&255,Ce[2]=ne>>>16&255,Ce[3]=ne>>>24&255,i.check=o(i.check,Ce,4,0)),ne=0,le=0,i.mode=E;case E:for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<>8),512&i.flags&&(Ce[0]=255&ne,Ce[1]=ne>>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0,i.mode=A;case A:if(1024&i.flags){for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0}else i.head&&(i.head.extra=null);i.mode=C;case C:if(1024&i.flags&&((pe=i.length)>oe&&(pe=oe),pe&&(i.head&&(we=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),s.arraySet(i.head.extra,ee,ie,pe,we)),512&i.flags&&(i.check=o(i.check,ee,pe,ie)),oe-=pe,ie+=pe,i.length-=pe),i.length))break e;i.length=0,i.mode=R;case R:if(2048&i.flags){if(0===oe)break e;pe=0;do{we=ee[ie+pe++],i.head&&we&&i.length<65536&&(i.head.name+=String.fromCharCode(we))}while(we&&pe>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=k;break;case D:for(;le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=7&le,le-=7&le,i.mode=Y;break}for(;le<3;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=1)){case 0:i.mode=I;break;case 1:if(de(i),i.mode=U,t===p){ne>>>=2,le-=2;break e}break;case 2:i.mode=V;break;case 3:e.msg="invalid block type",i.mode=Z}ne>>>=2,le-=2;break;case I:for(ne>>>=7&le,le-=7≤le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Z;break}if(i.length=65535&ne,ne=0,le=0,i.mode=F,t===p)break e;case F:i.mode=N;case N:if(pe=i.length){if(pe>oe&&(pe=oe),pe>ae&&(pe=ae),0===pe)break e;s.arraySet(te,ee,ie,pe,re),oe-=pe,ie+=pe,ae-=pe,re+=pe,i.length-=pe;break}i.mode=k;break;case V:for(;le<14;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=5,le-=5,i.ndist=1+(31&ne),ne>>>=5,le-=5,i.ncode=4+(15&ne),ne>>>=4,le-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Z;break}i.have=0,i.mode=O;case O:for(;i.have>>=3,le-=3}for(;i.have<19;)i.lens[Re[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,xe={bits:i.lenbits},Pe=n(l,i.lens,0,19,i.lencode,0,i.work,xe),i.lenbits=xe.bits,Pe){e.msg="invalid code lengths set",i.mode=Z;break}i.have=0,i.mode=j;case j:for(;i.have>>16&255,ve=65535&Ae,!((fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=fe,le-=fe,i.lens[i.have++]=ve;else{if(16===ve){for(Ee=fe+2;le>>=fe,le-=fe,0===i.have){e.msg="invalid bit length repeat",i.mode=Z;break}we=i.lens[i.have-1],pe=3+(3&ne),ne>>>=2,le-=2}else if(17===ve){for(Ee=fe+3;le>>=fe)),ne>>>=3,le-=3}else{for(Ee=fe+7;le>>=fe)),ne>>>=7,le-=7}if(i.have+pe>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Z;break}for(;pe--;)i.lens[i.have++]=we}}if(i.mode===Z)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Z;break}if(i.lenbits=9,xe={bits:i.lenbits},Pe=n(h,i.lens,0,i.nlen,i.lencode,0,i.work,xe),i.lenbits=xe.bits,Pe){e.msg="invalid literal/lengths set",i.mode=Z;break}if(i.distbits=6,i.distcode=i.distdyn,xe={bits:i.distbits},Pe=n(c,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,xe),i.distbits=xe.bits,Pe){e.msg="invalid distances set",i.mode=Z;break}if(i.mode=U,t===p)break e;case U:i.mode=G;case G:if(oe>=6&&ae>=258){e.next_out=re,e.avail_out=ae,e.next_in=ie,e.avail_in=oe,i.hold=ne,i.bits=le,a(e,ce),re=e.next_out,te=e.output,ae=e.avail_out,ie=e.next_in,ee=e.input,oe=e.avail_in,ne=i.hold,le=i.bits,i.mode===k&&(i.back=-1);break}for(i.back=0;ge=(Ae=i.lencode[ne&(1<>>16&255,ve=65535&Ae,!((fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>be)])>>>16&255,ve=65535&Ae,!(be+(fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=be,le-=be,i.back+=be}if(ne>>>=fe,le-=fe,i.back+=fe,i.length=ve,0===ge){i.mode=X;break}if(32&ge){i.back=-1,i.mode=k;break}if(64&ge){e.msg="invalid literal/length code",i.mode=Z;break}i.extra=15&ge,i.mode=z;case z:if(i.extra){for(Ee=i.extra;le>>=i.extra,le-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=H;case H:for(;ge=(Ae=i.distcode[ne&(1<>>16&255,ve=65535&Ae,!((fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>be)])>>>16&255,ve=65535&Ae,!(be+(fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=be,le-=be,i.back+=be}if(ne>>>=fe,le-=fe,i.back+=fe,64&ge){e.msg="invalid distance code",i.mode=Z;break}i.offset=ve,i.extra=15&ge,i.mode=$;case $:if(i.extra){for(Ee=i.extra;le>>=i.extra,le-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Z;break}i.mode=W;case W:if(0===ae)break e;if(pe=ce-ae,i.offset>pe){if((pe=i.offset-pe)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Z;break}pe>i.wnext?(pe-=i.wnext,me=i.wsize-pe):me=i.wnext-pe,pe>i.length&&(pe=i.length),_e=i.window}else _e=te,me=re-i.offset,pe=i.length;pe>ae&&(pe=ae),ae-=pe,i.length-=pe;do{te[re++]=_e[me++]}while(--pe);0===i.length&&(i.mode=G);break;case X:if(0===ae)break e;te[re++]=i.length,ae--,i.mode=G;break;case Y:if(i.wrap){for(;le<32;){if(0===oe)break e;oe--,ne|=ee[ie++]<=1&&0===I[A];A--);if(C>A&&(C=A),0===A)return h[c++]=20971520,h[c++]=20971520,u.bits=1,0;for(E=1;E0&&(0===e||1!==A))return-1;for(F[1]=0,P=1;P<15;P++)F[P+1]=F[P]+I[P];for(x=0;x852||2===e&&D>592)return 1;for(;;){b=P-S,d[x]v?(y=N[V+d[x]],M=k[B+d[x]]):(y=96,M=0),p=1<>S)+(m-=p)]=b<<24|y<<16|M|0}while(0!==m);for(p=1<>=1;if(0!==p?(T&=p-1,T+=p):T=0,x++,0==--I[P]){if(P===A)break;P=t[i+d[x]]}if(P>C&&(T&f)!==_){for(0===S&&(S=C),g+=E,L=1<<(R=P-S);R+S852||2===e&&D>592)return 1;h[_=T&f]=C<<24|R<<16|g-c|0}}return 0!==T&&(h[g+T]=P-S<<24|64<<16|0),u.bits=C,0}},{"../utils/common":3}],13:[function(e,t,i){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],14:[function(e,t,i){var s=e("../utils/common"),r=4,o=0,a=1,n=2;function l(e){for(var t=e.length;--t>=0;)e[t]=0}var h=0,c=1,d=2,u=29,p=256,m=p+1+u,_=30,f=19,g=2*m+1,v=15,b=16,y=7,M=256,w=16,P=17,x=18,E=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],A=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],C=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],R=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S=new Array(2*(m+2));l(S);var L=new Array(2*_);l(L);var D=new Array(512);l(D);var T=new Array(256);l(T);var k=new Array(u);l(k);var B,I,F,N=new Array(_);function V(e,t,i,s,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=s,this.max_length=r,this.has_stree=e&&e.length}function O(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function j(e){return e<256?D[e]:D[256+(e>>>7)]}function U(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function G(e,t,i){e.bi_valid>b-i?(e.bi_buf|=t<>b-e.bi_valid,e.bi_valid+=i-b):(e.bi_buf|=t<>>=1,i<<=1}while(--t>0);return i>>>1}function $(e,t,i){var s,r,o=new Array(v+1),a=0;for(s=1;s<=v;s++)o[s]=a=a+i[s-1]<<1;for(r=0;r<=t;r++){var n=e[2*r+1];0!==n&&(e[2*r]=H(o[n]++,n))}}function W(e){var t;for(t=0;t8?U(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Y(e,t,i,s){var r=2*t,o=2*i;return e[r]>1;i>=1;i--)q(e,o,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],q(e,o,1),s=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=s,o[2*r]=o[2*i]+o[2*s],e.depth[r]=(e.depth[i]>=e.depth[s]?e.depth[i]:e.depth[s])+1,o[2*i+1]=o[2*s+1]=r,e.heap[1]=r++,q(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,s,r,o,a,n,l=t.dyn_tree,h=t.max_code,c=t.stat_desc.static_tree,d=t.stat_desc.has_stree,u=t.stat_desc.extra_bits,p=t.stat_desc.extra_base,m=t.stat_desc.max_length,_=0;for(o=0;o<=v;o++)e.bl_count[o]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;im&&(o=m,_++),l[2*s+1]=o,s>h||(e.bl_count[o]++,a=0,s>=p&&(a=u[s-p]),n=l[2*s],e.opt_len+=n*(o+a),d&&(e.static_len+=n*(c[2*s+1]+a)));if(0!==_){do{for(o=m-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[m]--,_-=2}while(_>0);for(o=m;0!==o;o--)for(s=e.bl_count[o];0!==s;)(r=e.heap[--i])>h||(l[2*r+1]!==o&&(e.opt_len+=(o-l[2*r+1])*l[2*r],l[2*r+1]=o),s--)}}(e,t),$(o,h,e.bl_count)}function Q(e,t,i){var s,r,o=-1,a=t[1],n=0,l=7,h=4;for(0===a&&(l=138,h=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=a,a=t[2*(s+1)+1],++n>=7;s<_;s++)for(N[s]=r<<7,e=0;e<1<0?(e.strm.data_type===n&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return o;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return a;for(t=32;t=3&&0===e.bl_tree[2*R[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),l=e.opt_len+3+7>>>3,(h=e.static_len+3+7>>>3)<=l&&(l=h)):l=h=i+5,i+4<=l&&-1!==t?te(e,t,i,s):e.strategy===r||h===l?(G(e,(c<<1)+(s?1:0),3),K(e,S,L)):(G(e,(d<<1)+(s?1:0),3),function(e,t,i,s){var r;for(G(e,t-257,5),G(e,i-1,5),G(e,s-4,4),r=0;r>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(T[i]+p+1)]++,e.dyn_dtree[2*j(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){G(e,c<<1,3),z(e,M,S),function(e){16===e.bi_valid?(U(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":3}],15:[function(e,t,i){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/":[function(e,t,i){var s={};(0,e("./lib/utils/common").assign)(s,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=s},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")});var p=Object.freeze({__proto__:null});let pako=window.pako||p;pako.inflate||(pako=pako.default);const decompressColor=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function extract(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],positionsDecodeMatrix:e[11]}}function inflate(e){return{positions:new Uint16Array(pako.inflate(e.positions).buffer),normals:new Int8Array(pako.inflate(e.normals).buffer),indices:new Uint32Array(pako.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(pako.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(pako.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(pako.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(pako.inflate(e.meshColors).buffer),entityIDs:pako.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(pako.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(pako.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(pako.inflate(e.positionsDecodeMatrix).buffer)}}function load(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.meshPositions,h=i.meshIndices,c=i.meshEdgesIndices,d=i.meshColors,u=JSON.parse(i.entityIDs),p=i.entityMeshes,m=i.entityIsObjects,_=l.length,f=p.length;for(let g=0;gp[e]p[t]?1:0);for(let e=0;e1||(x[i]=e)}}for(let e=0;e1,_=decompressColor$3(m.subarray(4*t,4*t+3)),g=m[4*t+3]/255,v=r.subarray(c[t],i?r.length:c[t+1]),y=o.subarray(c[t],i?o.length:c[t+1]),P=a.subarray(d[t],i?a.length:d[t+1]),A=n.subarray(u[t],i?n.length:u[t+1]),C=l.subarray(p[t],p[t]+16);if(h){var E="geometry"+t;s.createGeometry({id:E,primitive:"triangles",positions:v,normals:y,indices:P,edgeIndices:A,positionsDecodeMatrix:C})}else{const e=t,i=(f[x[t]],{});s.createMesh(utils.apply(i,{id:e,primitive:"triangles",positions:v,normals:y,indices:P,edgeIndices:A,positionsDecodeMatrix:C,color:_,opacity:g}))}}let A=0;for(let e=0;e1){const t={},r="instance."+A++,o="geometry"+i,a=16*v[e],l=h.subarray(a,a+16);s.createMesh(utils.apply(t,{id:r,geometryId:o,matrix:l})),n.push(r)}else n.push(i)}if(n.length>0){const e={};s.createEntity(utils.apply(e,{id:r,isObject:!0,meshIds:n}))}}}const ParserV4={version:4,parse:function(e,t,i,s){load$3(e,t,inflate$3(extract$3(i)),s)}};let pako$4=window.pako||p;function extract$4(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],eachPrimitivePositionsAndNormalsPortion:e[5],eachPrimitiveIndicesPortion:e[6],eachPrimitiveEdgeIndicesPortion:e[7],eachPrimitiveColor:e[8],primitiveInstances:e[9],eachEntityId:e[10],eachEntityPrimitiveInstancesPortion:e[11],eachEntityMatricesPortion:e[12]}}function inflate$4(e){return{positions:new Float32Array(pako$4.inflate(e.positions).buffer),normals:new Int8Array(pako$4.inflate(e.normals).buffer),indices:new Uint32Array(pako$4.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako$4.inflate(e.edgeIndices).buffer),matrices:new Float32Array(pako$4.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(pako$4.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(pako$4.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(pako$4.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(pako$4.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(pako$4.inflate(e.primitiveInstances).buffer),eachEntityId:pako$4.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(pako$4.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(pako$4.inflate(e.eachEntityMatricesPortion).buffer)}}pako$4.inflate||(pako$4=pako$4.default);const decompressColor$4=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function load$4(e,t,i,s){s.positionsCompression="disabled",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.matrices,h=i.eachPrimitivePositionsAndNormalsPortion,c=i.eachPrimitiveIndicesPortion,d=i.eachPrimitiveEdgeIndicesPortion,u=i.eachPrimitiveColor,p=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,f=i.eachEntityMatricesPortion,g=h.length,v=p.length,b=new Uint8Array(g),y=m.length;for(let e=0;e1||(M[i]=e)}}for(let e=0;e1,l=decompressColor$4(u.subarray(4*e,4*e+3)),p=u[4*e+3]/255,_=r.subarray(h[e],t?r.length:h[e+1]),f=o.subarray(h[e],t?o.length:h[e+1]),v=a.subarray(c[e],t?a.length:c[e+1]),y=n.subarray(d[e],t?n.length:d[e+1]);if(i){var w="geometry"+e;s.createGeometry({id:w,primitive:"triangles",positions:_,normals:f,indices:v,edgeIndices:y})}else{const t=e,i=(m[M[e]],{});s.createMesh(utils.apply(i,{id:t,primitive:"triangles",positions:_,normals:f,indices:v,edgeIndices:y,color:l,opacity:p}))}}let P=0;for(let e=0;e1){const t={},r="instance."+P++,o="geometry"+i,a=16*f[e],h=l.subarray(a,a+16);s.createMesh(utils.apply(t,{id:r,geometryId:o,matrix:h})),n.push(r)}else n.push(i)}if(n.length>0){const e={};s.createEntity(utils.apply(e,{id:r,isObject:!0,meshIds:n}))}}}const ParserV5={version:5,parse:function(e,t,i,s){load$4(e,t,inflate$4(extract$4(i)),s)}};let pako$5=window.pako||p;function extract$5(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}function inflate$5(e){return{positions:new Uint16Array(pako$5.inflate(e.positions).buffer),normals:new Int8Array(pako$5.inflate(e.normals).buffer),indices:new Uint32Array(pako$5.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako$5.inflate(e.edgeIndices).buffer),matrices:new Float32Array(pako$5.inflate(e.matrices).buffer),reusedPrimitivesDecodeMatrix:new Float32Array(pako$5.inflate(e.reusedPrimitivesDecodeMatrix).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(pako$5.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(pako$5.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(pako$5.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColorAndOpacity:new Uint8Array(pako$5.inflate(e.eachPrimitiveColorAndOpacity).buffer),primitiveInstances:new Uint32Array(pako$5.inflate(e.primitiveInstances).buffer),eachEntityId:pako$5.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(pako$5.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(pako$5.inflate(e.eachEntityMatricesPortion).buffer),eachTileAABB:new Float64Array(pako$5.inflate(e.eachTileAABB).buffer),eachTileEntitiesPortion:new Uint32Array(pako$5.inflate(e.eachTileEntitiesPortion).buffer)}}pako$5.inflate||(pako$5=pako$5.default);const decompressColor$5=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function load$5(e,t,i,s){const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.matrices,h=i.reusedPrimitivesDecodeMatrix,c=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,u=i.eachPrimitiveEdgeIndicesPortion,p=i.eachPrimitiveColorAndOpacity,m=i.primitiveInstances,_=JSON.parse(i.eachEntityId),f=i.eachEntityPrimitiveInstancesPortion,g=i.eachEntityMatricesPortion,v=i.eachTileAABB,b=i.eachTileEntitiesPortion,y=c.length,M=m.length,w=_.length,P=b.length;let x=0;const E=new Uint32Array(y);for(let e=0;e1,_=t===y-1,f=r.subarray(c[t],_?r.length:c[t+1]),g=o.subarray(c[t],_?o.length:c[t+1]),v=a.subarray(d[t],_?a.length:d[t+1]),b=n.subarray(u[t],_?n.length:u[t+1]),M=decompressColor$5(p.subarray(4*t,4*t+3)),w=p[4*t+3]/255,C=x++;if(l){const e="geometry."+i+"."+t;k[e]||(s.createGeometry({id:e,rtcCenter:A,primitive:"triangles",positions:f,normals:g,indices:v,edgeIndices:b,positionsDecodeMatrix:h}),k[e]=!0),s.createMesh(utils.apply(I,{id:C,geometryId:e,matrix:P,color:M,opacity:w})),L.push(C)}else s.createMesh(utils.apply(I,{id:C,rtcCenter:A,primitive:"triangles",positions:f,normals:g,indices:v,edgeIndices:b,positionsDecodeMatrix:T,color:M,opacity:w})),L.push(C)}L.length>0&&s.createEntity(utils.apply(B,{id:b,isObject:!0,meshIds:L}))}}}const ParserV6={version:6,parse:function(e,t,i,s){load$5(e,t,inflate$5(extract$5(i)),s)}},parsers={};parsers[ParserV1.version]=ParserV1,parsers[ParserV2.version]=ParserV2,parsers[ParserV3.version]=ParserV3,parsers[ParserV4.version]=ParserV4,parsers[ParserV5.version]=ParserV5,parsers[ParserV6.version]=ParserV6;class XKTLoaderPlugin extends Plugin{constructor(e,t={}){super("XKTLoader",e,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults,this.includeTypes=t.includeTypes,this.excludeTypes=t.excludeTypes,this.excludeUnclassifiedObjects=t.excludeUnclassifiedObjects}get supportedVersions(){return Object.keys(parsers)}set dataSource(e){this._dataSource=e||new XKTDefaultDataSource}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||IFCObjectDefaults}get objectDefaults(){return this._objectDefaults}set includeTypes(e){this._includeTypes=e}get includeTypes(){return this._includeTypes}set excludeTypes(e){this._excludeTypes=e}get excludeTypes(){return this._excludeTypes}set excludeUnclassifiedObjects(e){this._excludeUnclassifiedObjects=!!e}get excludeUnclassifiedObjects(){return this._excludeUnclassifiedObjects}load(e={}){e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);const t=new PerformanceModel(this.viewer.scene,utils.apply(e,{isModel:!0})),i=t.id;if(!e.src&&!e.xkt)return this.error("load() param expected: src or xkt"),t;const s={};if(e.metaModelSrc||e.metaModelData){const r=e.includeTypes||this._includeTypes,o=e.excludeTypes||this._excludeTypes,a=e.objectDefaults||this._objectDefaults;if(r){s.includeTypesMap={};for(let e=0,t=r.length;e{this.viewer.metaScene.createMetaModel(i,a,{includeTypes:r,excludeTypes:o}),this.viewer.scene.canvas.spinner.processes--,e.src?this._loadModel(e.src,e,s,t):this._parseModel(e.xkt,e,s,t),t.once("destroyed",()=>{this.viewer.metaScene.destroyMetaModel(t.id)})};if(e.metaModelSrc){const t=e.metaModelSrc;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getMetaModel(t,e=>{this.viewer.scene.canvas.spinner.processes--,n(e)},e=>{this.error(`load(): Failed to load model metadata for model '${i} from '${t}' - ${e}`),this.viewer.scene.canvas.spinner.processes--})}else e.metaModelData&&n(e.metaModelData)}else e.src?this._loadModel(e.src,e,s,t):this._parseModel(e.xkt,e,s,t);return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getXKT(t.src,e=>{this._parseModel(e,t,i,s),r.processes--},e=>{r.processes--,this.error(e),s.fire("error",e)})}_parseModel(e,t,i,s){const r=new DataView(e),o=new Uint8Array(e),a=r.getUint32(0,!0),n=parsers[a];if(!n)return void this.error("Unsupported .XKT file version: "+a+" - this XKTLoaderPlugin supports versions "+Object.keys(parsers));this.log("Loading .xkt V"+a);const l=r.getUint32(4,!0),h=[];let c=4*(l+2);for(let e=0;e{s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1)})}}const ModelIFCObjectColors={IfcSpace:{opacity:.3},IfcWindow:{opacity:.4},IfcOpeningElement:{opacity:.3},IfcPlate:{opacity:.3}},ViewerIFCObjectColors={IfcRoof:{colorize:[.837255,.203922,.270588],priority:0},IfcSlab:{colorize:[.637255,.603922,.670588],priority:0},IfcWall:{colorize:[.537255,.337255,.237255],priority:0},IfcWallStandardCase:{colorize:[.537255,.337255,.237255],priority:0},IfcCovering:{colorize:[.8470588235,.427450980392,0],priority:0},IfcDoor:{colorize:[.637255,.603922,.670588],priority:1},IfcStair:{colorize:[.637255,.603922,.670588],priority:2},IfcStairFlight:{colorize:[.637255,.603922,.670588],priority:2},IfcProxy:{colorize:[.137255,.403922,.870588],priority:2},IfcRamp:{colorize:[.8470588235,.427450980392,0],priority:2},IfcColumn:{colorize:[.137255,.403922,.870588],priority:3},IfcBeam:{colorize:[.137255,.403922,.870588],priority:3},IfcCurtainWall:{colorize:[.137255,.403922,.870588],priority:3},IfcPlate:{colorize:[.8470588235,.427450980392,0,.5],opacity:.5,priority:3},IfcTransportElement:{colorize:[.8470588235,.427450980392,0],priority:3},IfcFooting:{colorize:[.8470588235,.427450980392,0],priority:3},IfcRailing:{colorize:[.137255,.403922,.870588],priority:4},IfcFurnishingElement:{colorize:[.137255,.403922,.870588],priority:4},IfcFurniture:{colorize:[.8470588235,.427450980392,0],priority:4},IfcSystemFurnitureElement:{colorize:[.8470588235,.427450980392,0],priority:4},IfcFlowSegment:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowitting:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowTerminal:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowController:{colorize:[.8470588235,.427450980392,0],priority:5},IfcFlowFitting:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDuctSegment:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDistributionFlowElement:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDuctFitting:{colorize:[.8470588235,.427450980392,0],priority:5},IfcLightFixture:{colorize:[.8470588235,.8470588235,.870588],priority:5},IfcAirTerminal:{colorize:[.8470588235,.427450980392,0],priority:6},IfcOpeningElement:{colorize:[.137255,.403922,.870588],opacity:.3,priority:6},IfcSpace:{colorize:[.137255,.403922,.870588],opacity:.5,priority:6},IfcWindow:{colorize:[.137255,.403922,.870588],opacity:.4,priority:6},IfcBuildingElementProxy:{colorize:[.5,.5,.5]},IfcSite:{colorize:[.137255,.403922,.870588]},IfcMember:{colorize:[.8470588235,.427450980392,0]},DEFAULT:{colorize:[.5,.5,.5],priority:10}};class ModelsContextMenu extends ContextMenu{constructor(e={}){const t=[[{title:"Load",getEnabled:function(e){return!e.bimViewer.isModelLoaded(e.modelId)},doAction:function(e){e.bimViewer.loadModel(e.modelId)}},{title:"Unload",getEnabled:function(e){return e.bimViewer.isModelLoaded(e.modelId)},doAction:function(e){e.bimViewer.unloadModel(e.modelId)}}]];!!e.enableEditModels&&t.push([{title:"Edit",getEnabled:function(e){return!0},doAction:function(e){e.bimViewer.editModel(e.modelId)}},{title:"Delete",getEnabled:function(e){return!0},doAction:function(e){e.bimViewer.deleteModel(e.modelId)}}]),t.push([{title:"Load All",getEnabled:function(e){const t=e.bimViewer,i=t.getModelIds();return t.getLoadedModelIds().length0},doAction:function(e){e.bimViewer.unloadAllModels()}}]),t.push([{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]),super({context:e.context,items:t})}}const tempVec3$4=math.vec3();class ModelsExplorer extends Controller{constructor(e,t){if(super(e,t),!t.modelsTabElement)throw"Missing config: modelsTabElement";if(!t.unloadModelsButtonElement)throw"Missing config: unloadModelsButtonElement";if(!t.modelsElement)throw"Missing config: modelsElement";if(this._enableAddModels=!!t.enableEditModels,this._modelsTabElement=t.modelsTabElement,this._loadModelsButtonElement=t.loadModelsButtonElement,this._unloadModelsButtonElement=t.unloadModelsButtonElement,this._addModelButtonElement=t.addModelButtonElement,this._modelsElement=t.modelsElement,this._modelsTabButtonElement=this._modelsTabElement.querySelector(".xeokit-tab-btn"),!this._modelsTabButtonElement)throw"Missing DOM element: ,xeokit-tab-btn";this._xktLoader=new XKTLoaderPlugin(this.viewer,{objectDefaults:ModelIFCObjectColors}),this._modelsContextMenu=new ModelsContextMenu({enableEditModels:t.enableEditModels}),this._modelsInfo={},this._numModels=0,this._numModelsLoaded=0,this._projectId=null}loadProject(e,t,i){this.server.getProject(e,i=>{this.unloadProject(),this._projectId=e,this._modelsInfo={},this._numModels=0,this._parseProject(i,t),this._numModelsLoaded0&&this._unloadModelsButtonElement.classList.remove("disabled"),this._enableAddModels&&this._addModelButtonElement.classList.remove("disabled")},e=>{this.error(e),i&&i(e)})}_parseProject(e,t){this._buildModelsMenu(e),this._parseViewerConfigs(e),this._parseViewerContent(e,()=>{this._parseViewerState(e,()=>{t()})})}_buildModelsMenu(e){var t="";const i=e.models||[];this._modelsInfo={},this._numModels=i.length;for(let e=0,s=i.length;e",t+=""+s.name+"",t+=""}this._modelsElement.innerHTML=t;for(let e=0,t=i.length;e{r.checked?this.loadModel(s):this.unloadModel(t.id)}),o.addEventListener("click",()=>{!!this.viewer.scene.models[s]?this.unloadModel(t.id):this.loadModel(s)}),o.oncontextmenu=(e=>{this._modelsContextMenu.context={bimViewer:this.bimViewer,viewer:this.viewer,modelId:s},this._modelsContextMenu.show(e.pageX,e.pageY),e.preventDefault()})}}_parseViewerConfigs(e){const t=e.viewerConfigs;t&&this.bimViewer.setConfigs(t)}_parseViewerContent(e,t){const i=e.viewerContent;i?this._parseModelsLoaded(i,()=>{t()}):t()}_parseModelsLoaded(e,t){const i=e.modelsLoaded;i&&0!==i.length?this._loadNextModel(i.slice(0),t):t()}_loadNextModel(e,t){if(0===e.length)return void t();const i=e.pop();this.loadModel(i,()=>{this._loadNextModel(e,t)},()=>{this._loadNextModel(e,t)})}_parseViewerState(e,t){const i=e.viewerState;i?this.bimViewer.setViewerState(i,t):t()}unloadProject(){if(!this._projectId)return;const e=this.viewer.scene.models;for(var t in e)if(e.hasOwnProperty(t)){e[t].destroy()}this._modelsElement.innerHTML="",this._numModelsLoaded=0,this._loadModelsButtonElement.classList.add("disabled"),this._unloadModelsButtonElement.classList.add("disabled"),this._enableAddModels&&this._addModelButtonElement.classList.add("disabled");const i=this._projectId;this._projectId=null,this.fire("projectUnloaded",{projectId:i})}getLoadedProjectId(){return this._projectId}getModelIds(){return Object.keys(this._modelsInfo)}loadModel(e,t,i){if(!this._projectId){const e="No project currently loaded";return this.error(e),void(i&&i(e))}const s=this._modelsInfo[e];if(!s){const e="Model not in currently loaded project";return this.error(e),void(i&&i(e))}this.bimViewer._busyModal.show("Loading: "+s.name),this.server.getMetadata(this._projectId,e,r=>{this.server.getGeometry(this._projectId,e,i=>{const o="model"===(s.objectColorSource||this.bimViewer.getObjectColorSource())?ModelIFCObjectColors:ViewerIFCObjectColors;this._xktLoader.load({id:e,metaModelData:r,xkt:i,objectDefaults:o,excludeUnclassifiedObjects:!0,position:s.position,scale:s.scale,rotation:s.rotation,matrix:s.matrix,edges:!1!==s.edges,saoEnabled:s.saoEnabled}).on("loaded",()=>{document.getElementById(""+e).checked=!0;const i=this.viewer.scene,s=i.getAABB(i.visibleObjectIds);this._numModelsLoaded++,this._unloadModelsButtonElement.classList.remove("disabled"),this._numModelsLoaded{this.bimViewer._busyModal.hide(),this.error(e),i&&i(e)})},e=>{this.bimViewer._busyModal.hide(),this.error(e),i&&i(e)})}unloadModel(e){const t=this.viewer.scene.models[e];if(!t)return void this.error("Model not loaded: "+e);t.destroy(),document.getElementById(""+e).checked=!1;document.getElementById("span-"+e);this._numModelsLoaded--,this._numModelsLoaded>0?this._unloadModelsButtonElement.classList.remove("disabled"):this._unloadModelsButtonElement.classList.add("disabled"),this._numModelsLoaded{e.preventDefault()}),this._onObjectVisibility=this._viewer.scene.on("objectVisibility",e=>{if(this._muteSceneEvents)return;const t=e.id,i=this._objectNodes[t];if(!i)return;const s=e.visible;if(!(s!==i.checked))return;this._muteTreeEvents=!0,i.checked=s,s?i.numVisibleEntities++:i.numVisibleEntities--;const r=document.getElementById(i.nodeId);r&&(r.checked=s);let o=i.parent;for(;o;){o.checked=s,s?o.numVisibleEntities++:o.numVisibleEntities--;const e=document.getElementById(o.nodeId);if(e){const t=o.numVisibleEntities>0;t!==e.checked&&(e.checked=t)}o=o.parent}this._muteTreeEvents=!1}),this.switchExpandHandler=(e=>{e.preventDefault(),e.stopPropagation();const t=e.target;this._expandSwitchElement(t)}),this.switchCollapseHandler=(e=>{e.preventDefault(),e.stopPropagation();const t=e.target;this._collapseSwitchElement(t)}),this._checkboxChangeHandler=(e=>{if(this._muteTreeEvents)return;this._muteSceneEvents=!0;const t=e.target,i=t.checked,s=t.id,r=this._nodeToObjectID(s),o=this._objectNodes[r],a=this._viewer.scene.objects;let n=0;this._withNodeTree(o,e=>{const t=e.objectId,s=e.nodeId,r=a[t],o=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,o&&i!==e.checked&&n++,e.checked=i;const l=document.getElementById(s);l&&(l.checked=i),r&&(r.visible=i)});let l=o.parent;for(;l;){l.checked=i;const e=document.getElementById(l.nodeId);i?l.numVisibleEntities+=n:l.numVisibleEntities-=n;const t=l.numVisibleEntities>0;t!==e.checked&&(e.checked=t),l=l.parent}this._muteSceneEvents=!1}),this._hierarchy=r.hierarchy||"containment",this._autoExpandDepth=r.autoExpandDepth||0,this._createNodes())}_nodeToObjectID(e){return e.substring(this._baseId.length)}_objectToNodeID(e){return this._baseId+e}setAutoExpandDepth(e=0){this._autoExpandDepth=e}setHierarchy(e){this._hierarchy!==e&&(this._hierarchy=e,this._createNodes())}_createNodes(){switch(this._rootElement&&(this._rootElement.parentNode.removeChild(this._rootElement),this._rootElement=null),this._rootNodes=[],this._objectNodes={},this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this._treeViewPlugin.error("Failed to build storeys hierarchy for model '"+this._metaModel.id+"' - perhaps this model is not an IFC model?");break;case"types":this._createTypesNodes();break;case"containment":default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}_findEmptyNodes(e=this._rootMetaObject,t=0){const i=this._treeViewPlugin.viewer.scene,s=e.children,r=e.id,o=i.objects[r];if(e._countEntities=0,o&&e._countEntities++,s)for(let t=0,i=s.length;t{e.aabb&&r.aabb||(e.aabb||(e.aabb=t.getAABB(s.getObjectIDsInSubtree(e.objectId))),r.aabb||(r.aabb=t.getAABB(s.getObjectIDsInSubtree(r.objectId))));let o=0;return o=i.xUp?0:i.yUp?1:2,e.aabb[o]>r.aabb[o]?-1:e.aabb[o]s?1:0}_synchNodesToEntities(){const e=this._rootMetaObject.getObjectIDsInSubtree(),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects;for(let s=0,r=e.length;sthis._createNodeElement(e)),t=document.createElement("ul");e.forEach(e=>{t.appendChild(e)}),this._containerElement.appendChild(t),this._rootElement=t}_createNodeElement(e){const t=document.createElement("li"),i=e.nodeId;if(t.id="node-"+i,e.children.length>0){const e="switch-"+i,s=document.createElement("a");s.href="#",s.id=e,s.textContent="+",s.classList.add("plus"),s.addEventListener("click",this.switchExpandHandler),t.appendChild(s)}const s=document.createElement("input");s.id=i,s.type="checkbox",s.checked=e.checked,s.addEventListener("change",this._checkboxChangeHandler),t.appendChild(s);const r=document.createElement("span");return r.textContent=e.title,t.appendChild(r),r.oncontextmenu=(t=>{this._treeViewPlugin.fire("contextmenu",{event:t,viewer:this._viewer,treeViewPlugin:this._treeViewPlugin,treeViewNode:e}),t.preventDefault()}),r.onclick=(t=>{this._treeViewPlugin.fire("nodeTitleClicked",{event:t,viewer:this._viewer,treeViewPlugin:this._treeViewPlugin,treeViewNode:e}),t.preventDefault()}),t}expandToDepth(e){const t=(i,s)=>{if(s===e)return;const r="switch-"+i.nodeId,o=document.getElementById(r);if(o){this._expandSwitchElement(o);const e=i.children;for(var a=0,n=e.length;athis._createNodeElement(e)),o=document.createElement("ul");r.forEach(e=>{o.appendChild(e)}),t.appendChild(o),e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",this.switchExpandHandler),e.addEventListener("click",this.switchCollapseHandler)}_collapseNode(e){const t="switch-"+this._objectToNodeID(e),i=document.getElementById(t);this._collapseSwitchElement(i)}_collapseSwitchElement(e){if(!e)return;const t=e.parentElement;if(!t)return;const i=t.querySelector("ul");i&&(t.removeChild(i),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",this.switchCollapseHandler),e.addEventListener("click",this.switchExpandHandler))}destroy(){this._rootElement&&!this._destroyed&&(this._rootElement.parentNode.removeChild(this._rootElement),this._viewer.scene.off(this._onObjectVisibility),this._destroyed=!0,idMap$1.removeItem(this._id))}}class TreeViewPlugin extends Plugin{constructor(e,t={}){if(super("TreeViewPlugin",e),t.containerElement){if(this._containerElement=t.containerElement,this._modelTreeViews={},this._modelTreeViews={},this._autoAddModels=!1!==t.autoAddModels,this._autoExpandDepth=t.autoExpandDepth||0,this._sortNodes=!1!==t.sortNodes,this._pruneEmptyNodes=!1!==t.pruneEmptyNodes,this._autoAddModels){const e=Object.keys(this.viewer.scene.models);for(let t=0,i=e.length;t{this.viewer.metaScene.metaModels[e]&&this.addModel(e)})}this.hierarchy=t.hierarchy}else this.error("Config expected: containerElement")}set hierarchy(e){"containment"!==(e=e||"containment")&&"storeys"!==e&&"types"!==e&&(this.error("Unsupported value for `hierarchy' - defaulting to 'containment'"),e="containment"),this._hierarchy=e;for(let e in this._modelTreeViews)this._modelTreeViews.hasOwnProperty(e)&&this._modelTreeViews[e].setHierarchy(this._hierarchy)}get hierarchy(){return this._hierarchy}addModel(e,t={}){if(!this._containerElement)return;const i=this.viewer.scene.models[e];if(!i)throw"Model not found: "+e;const s=this.viewer.metaScene.metaModels[e];s?this._modelTreeViews[e]?this.warn("Model already added: "+e):(this._modelTreeViews[e]=new ModelTreeView(this.viewer,this,i,s,{containerElement:this._containerElement,autoExpandDepth:this._autoExpandDepth,hierarchy:this._hierarchy,sortNodes:this._sortNodes,pruneEmptyNodes:this._pruneEmptyNodes,rootName:t.rootName}),i.on("destroyed",()=>{this.removeModel(i.id)})):this.error("MetaModel not found: "+e)}removeModel(e){if(!this._containerElement)return;const t=this._modelTreeViews[e];t?(t.destroy(),delete this._modelTreeViews[e]):this.warn("Model not added: "+e)}collapse(){for(let e in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(e)){this._modelTreeViews[e].collapse()}}showNode(e){this.unShowNode();const t=this.viewer.metaScene.metaObjects[e];if(!t)return void this.error("MetaObject not found: "+e);const i=t.metaModel.id,s=this._modelTreeViews[i];s?s.showNode(e):this.error("Object not in this TreeView: "+e)}unShowNode(){for(let e in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(e)){this._modelTreeViews[e].unShowNode()}}expandToDepth(e){for(let t in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(t)){const i=this._modelTreeViews[t];i.collapse(),i.expandToDepth(e)}}withNodeTree(e,t){t(e);const i=e.children;if(i)for(let e=0,s=i.length;e{e.objectId&&s.push(e.objectId)});const r=i.getAABB(s);t.cameraControl.pivotPos=math.getAABB3Center(r,tempVec3$5),i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsVisible(i.objectIds,!1),i.setObjectsPickable(i.objectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsVisible(s,!0),i.setObjectsPickable(s,!0),t.cameraFlight.flyTo({aabb:r},()=>{})}}],[{title:"View Fit",doAction:function(e){const t=e.viewer,i=t.scene,s=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&s.push(e.objectId)}),i.setObjectsVisible(s,!0),i.setObjectsHighlighted(s,!0);const r=i.getAABB(s);t.cameraFlight.flyTo({aabb:r,duration:.5},()=>{setTimeout(function(){i.setObjectsHighlighted(i.highlightedObjectIds,!1)},500)}),t.cameraControl.pivotPos=math.getAABB3Center(r)}},{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}}],[{title:"Hide",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.visible=!1)}})}},{title:"Hide Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.visibleObjectIds,!1),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1),t.setObjectsHighlighted(t.highlightedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.visible=!0)}})}},{title:"Hide All",getEnabled:function(e){return e.viewer.scene.visibleObjectIds.length>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}}],[{title:"Show",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.visible=!0,i.xrayed&&(i.pickable=!0),i.xrayed=!1,i.selected=!1)}})}},{title:"Show Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.visible=!1)}})}},{title:"Show All",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.xrayed=!0,i.visible=!0,i.pickable=!1)}})}},{title:"Undo X-Ray",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.xrayed=!1,i.pickable=!0)}})}},{title:"X-Ray Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsHighlighted(t.highlightedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.xrayed=!1,i.pickable=!0)}})}},{title:"X-Ray All",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1)}},{title:"X-Ray None",getEnabled:function(e){return e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene,i=t.xrayedObjectIds;t.setObjectsPickable(i,!0),t.setObjectsXRayed(i,!1)}}],[{title:"Select",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!0,i.visible=!0)}})}},{title:"Undo Select",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!1)}})}},{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}const tempVec3$6=math.vec3();class ObjectsExplorer extends Controller{constructor(e,t={}){if(super(e),!t.objectsTabElement)throw"Missing config: objectsTabElement";if(!t.showAllObjectsButtonElement)throw"Missing config: showAllObjectsButtonElement";if(!t.hideAllObjectsButtonElement)throw"Missing config: hideAllObjectsButtonElement";if(!t.objectsElement)throw"Missing config: objectsElement";if(this._objectsTabElement=t.objectsTabElement,this._showAllObjectsButtonElement=t.showAllObjectsButtonElement,this._hideAllObjectsButtonElement=t.hideAllObjectsButtonElement,this._objectsTabButtonElement=this._objectsTabElement.querySelector(".xeokit-tab-btn"),!this._objectsTabButtonElement)throw"Missing DOM element: ,xeokit-tab-btn";const i=t.objectsElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,hierarchy:"containment",autoAddModels:!1,pruneEmptyNodes:!0}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{if(this.viewer.metaScene.metaModels[e]){const t=this.bimViewer._modelsExplorer.getModelInfo(e);if(!t)return;this._treeView.addModel(e,{rootName:t.name})}}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse()})}setEnabled(e){e?(this._objectsTabButtonElement.classList.remove("disabled"),this._showAllObjectsButtonElement.classList.remove("disabled"),this._hideAllObjectsButtonElement.classList.remove("disabled")):(this._objectsTabButtonElement.classList.add("disabled"),this._showAllObjectsButtonElement.classList.add("disabled"),this._hideAllObjectsButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$7=math.vec3();class ClassesExplorer extends Controller{constructor(e,t={}){if(super(e),!t.classesTabElement)throw"Missing config: classesTabElement";if(!t.showAllClassesButtonElement)throw"Missing config: showAllClassesButtonElement";if(!t.hideAllClassesButtonElement)throw"Missing config: hideAllClassesButtonElement";if(!t.classesElement)throw"Missing config: classesElement";if(this._classesTabElement=t.classesTabElement,this._showAllClassesButtonElement=t.showAllClassesButtonElement,this._hideAllClassesButtonElement=t.hideAllClassesButtonElement,this._classesTabButtonElement=this._classesTabElement.querySelector(".xeokit-tab-btn"),!this._classesTabButtonElement)throw"Missing DOM element: xeokit-tab-btn";const i=t.classesElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,hierarchy:"types",autoAddModels:!1,pruneEmptyNodes:!0}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{if(this.viewer.metaScene.metaModels[e]){const t=this.bimViewer._modelsExplorer.getModelInfo(e);if(!t)return;this._treeView.addModel(e,{rootName:t.name})}}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse()})}setEnabled(e){e?(this._classesTabButtonElement.classList.remove("disabled"),this._showAllClassesButtonElement.classList.remove("disabled"),this._hideAllClassesButtonElement.classList.remove("disabled")):(this._classesTabButtonElement.classList.add("disabled"),this._showAllClassesButtonElement.classList.add("disabled"),this._hideAllClassesButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$8=math.vec3();class StoreysExplorer extends Controller{constructor(e,t={}){if(super(e),!t.storeysTabElement)throw"Missing config: storeysTabElement";if(!t.showAllStoreysButtonElement)throw"Missing config: showAllStoreysButtonElement";if(!t.hideAllStoreysButtonElement)throw"Missing config: hideAllStoreysButtonElement";if(!t.storeysElement)throw"Missing config: storeysElement";if(this._storeysTabElement=t.storeysTabElement,this._showAllStoreysButtonElement=t.showAllStoreysButtonElement,this._hideAllStoreysButtonElement=t.hideAllStoreysButtonElement,this._storeysTabButtonElement=this._storeysTabElement.querySelector(".xeokit-tab-btn"),!this._storeysTabButtonElement)throw"Missing DOM element: .xeokit-tab-btn";const i=t.storeysElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,autoAddModels:!1,hierarchy:"storeys",autoExpandDepth:1}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode,pruneEmptyNodes:!0},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{const t=this.bimViewer._modelsExplorer.getModelInfo(e);t&&this._treeView.addModel(e,{rootName:t.name})}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse(),this._treeView.expandToDepth(1)})}setEnabled(e){e?(this._storeysTabButtonElement.classList.remove("disabled"),this._showAllStoreysButtonElement.classList.remove("disabled"),this._hideAllStoreysButtonElement.classList.remove("disabled")):(this._storeysTabButtonElement.classList.add("disabled"),this._showAllStoreysButtonElement.classList.add("disabled"),this._hideAllStoreysButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}selectStorey(e,t){const i=this.viewer.metaScene.metaObjects[e];if(!i)return void this.error("selectStorey() - object is not found: '"+e+"'");if("IfcBuildingStorey"!==i.type)return void this.error("selectStorey() - object is not found: '"+e+"'");const s=i.getObjectIDsInSubtree();this._selectObjects(s,t)}_selectObjects(e,t){const i=this.viewer.scene,s=i.getAABB(e);this.viewer.cameraControl.pivotPos=math.getAABB3Center(s,tempVec3$8),t?(i.setObjectsXRayed(i.objectIds,!0),i.setObjectsVisible(i.objectIds,!0),i.setObjectsPickable(i.objectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsXRayed(e,!1),i.setObjectsVisible(e,!0),i.setObjectsPickable(e,!0),this.viewer.cameraFlight.flyTo({aabb:s},()=>{setTimeout(function(){i.setObjectsVisible(i.xrayedObjectIds,!1),i.setObjectsXRayed(i.xrayedObjectIds,!1)},500),t()})):(i.setObjectsVisible(i.objectIds,!1),i.setObjectsPickable(i.xrayedObjectIds,!0),i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsVisible(e,!0),this.viewer.cameraFlight.jumpTo({aabb:s}))}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$9=math.vec3(),newLook=math.vec3(),newEye=math.vec3(),newUp=math.vec3(),newLookEyeVec=math.vec3();class CameraFlightAnimation extends Component{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=math.vec3(),this._eye1=math.vec3(),this._up1=math.vec3(),this._look2=math.vec3(),this._eye2=math.vec3(),this._up2=math.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,a,n,l,h;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)a=e.eye,n=e.look,l=e.up;else if(e.eye)a=e.eye;else if(e.look)n=e.look;else{let s=e;if((utils.isNumeric(s)||utils.isString(s))&&(h=s,!(s=this.scene.components[h])))return this.error("Component not found: "+utils.inQuotes(h)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const c=e.poi;if(o){if(o[3]=1;e>1&&(e=1);const i=this.easing?CameraFlightAnimation._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(math.subVec3(s.eye,s.look,newLookEyeVec),s.eye=math.lerpVec3(i,0,1,this._eye1,this._eye2,newEye),s.look=math.subVec3(newEye,newLookEyeVec,newLook)):this._flyingLook&&(s.look=math.lerpVec3(i,0,1,this._look1,this._look2,newLook),s.up=math.lerpVec3(i,0,1,this._up1,this._up2,newUp)):this._flyingEyeLookUp&&(s.eye=math.lerpVec3(i,0,1,this._eye1,this._eye2,newEye),s.look=math.lerpVec3(i,0,1,this._look1,this._look2,newLook),s.up=math.lerpVec3(i,0,1,this._up1,this._up2,newUp)),this._projection2){const t="ortho"===this._projection2?CameraFlightAnimation._easeOutExpo(e,0,1,1):CameraFlightAnimation._easeInCubic(e,0,1,1);s.customProjection.matrix=math.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);t?this.stop():core.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=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()}}const screenPos=math.vec4(),viewPos=math.vec4(),worldPos=math.vec4(),tempVec3a$u=math.vec3(),tempVec3b$1=math.vec3(),tempVec3c$1=math.vec3(),tempVec4a$2=math.vec4(),tempVec4b$2=math.vec4(),tempVec4c$2=math.vec4();class PanController{constructor(e){this._scene=e,this._inverseProjectMat=math.mat4(),this._transposedProjectMat=math.mat4(),this._inverseOrthoProjectMat=math.mat4(),this._transposedOrthoProjectMat=math.mat4(),this._inverseViewMat=math.mat4(),this._projMatDirty=!0,this._viewMatDirty=!0,this._sceneDiagSizeDirty=!0,this._sceneDiagSize=1,this._onCameraOrthoProjMatrix=this._scene.camera.ortho.on("matrix",()=>{this._projMatDirty=!0}),this._onCameraPerspectiveProjMatrix=this._scene.camera.perspective.on("matrix",()=>{this._projMatDirty=!0}),this._onCameraViewMatrix=this._scene.camera.on("viewMatrix",()=>{this._viewMatDirty=!0}),this._onSceneBoundary=this._scene.scene.on("boundary",()=>{this._sceneDiagSizeDirty=!0})}dolly(e,t,i){const s=this._scene.camera;if("perspective"===s.projection)s.ortho.scale=s.ortho.scale-i,this._dollyToWorldPos(e,i);else if("ortho"===s.projection){const e=this._unprojectOrtho(t,viewPos,tempVec4a$2);s.ortho.scale=s.ortho.scale-i,s.ortho._update();const r=this._unprojectOrtho(t,viewPos,tempVec4b$2),o=math.subVec3(r,e,tempVec4c$2),a=math.mulVec3Scalar(math.normalizeVec3(math.subVec3(s.look,s.eye,tempVec3a$u)),-i,tempVec3b$1),n=math.addVec3(o,a,tempVec3c$1);s.eye=[s.eye[0]-n[0],s.eye[1]-n[1],s.eye[2]-n[2]],s.look=[s.look[0]-n[0],s.look[1]-n[1],s.look[2]-n[2]]}}_getInverseProjectMat(){return this._updateProjMatrices(),this._inverseProjectMat}_getTransposedProjectMat(){return this._updateProjMatrices(),this._transposedProjectMat}_getInverseOrthoProjectMat(){return this._updateProjMatrices(),this._inverseOrthoProjectMat}_getTransposedOrthoProjectMat(){return this._updateProjMatrices(),this._transposedOrthoProjectMat}_updateProjMatrices(){this._projMatDirty&&(math.inverseMat4(this._scene.camera.perspective.matrix,this._inverseProjectMat),math.inverseMat4(this._scene.camera.ortho.matrix,this._inverseOrthoProjectMat),math.transposeMat4(this._scene.camera.perspective.matrix,this._transposedProjectMat),math.transposeMat4(this._scene.camera.ortho.matrix,this._transposedOrthoProjectMat),this._projMatDirty=!1)}_getInverseViewMat(){return this._viewMatDirty&&math.inverseMat4(this._scene.camera.viewMatrix,this._inverseViewMat),this._inverseViewMat}_getSceneDiagSize(){return this._sceneDiagSizeDirty&&(this._sceneDiagSize=math.getAABB3Diag(this._scene.aabb)),this._sceneDiagSize}_unprojectPerspective(e,t,i){const s=this._scene.canvas.canvas,r=this._getTransposedProjectMat(),o=r.subarray(8,12),a=r.subarray(12),n=[0,0,-this._getSceneDiagSize(),1],l=math.dotVec4(n,o)/math.dotVec4(n,a),h=this._getInverseProjectMat(),c=this._getInverseViewMat(),d=s.offsetWidth/2,u=s.offsetHeight/2;screenPos[0]=(e[0]-d)/d,screenPos[1]=(e[1]-u)/u,screenPos[2]=l,screenPos[3]=1,math.mulMat4v4(h,screenPos,t),math.mulVec3Scalar(t,1/t[3]),t[3]=1,t[1]*=-1,math.mulMat4v4(c,t,i)}_unprojectOrtho(e,t,i){const s=this._scene.canvas.canvas,r=this._getTransposedOrthoProjectMat(),o=r.subarray(8,12),a=r.subarray(12),n=[0,0,-this._getSceneDiagSize(),1],l=math.dotVec4(n,o)/math.dotVec4(n,a),h=this._getInverseOrthoProjectMat(),c=this._getInverseViewMat(),d=s.offsetWidth/2,u=s.offsetHeight/2;return screenPos[0]=(e[0]-d)/d,screenPos[1]=(e[1]-u)/u,screenPos[2]=l,screenPos[3]=1,math.mulMat4v4(h,screenPos,t),math.mulVec3Scalar(t,1/t[3]),t[3]=1,t[1]*=-1,math.mulMat4v4(c,t,i),i}_dollyToWorldPos(e,t){const i=this._scene.camera,s=math.subVec3(e,i.eye,tempVec3a$u);if(math.lenVec3(s){this._cameraDirty=!0}),this._onProjMatrix=this._scene.camera.on("projMatrix",()=>{this._cameraDirty=!0}),this._onTick=this._scene.on("tick",()=>{this.updatePivotElement()})}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){math.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,math.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);const o=t.canvas.getBoundingClientRect();this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-12+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-12+"px"),this._cameraDirty=!1}}setPivotElement(e){this._pivotElement=e}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=math.lookAtMat4v(e.eye,e.look,e.worldUp);math.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=math.distVec3(e.eye,i),t=math.inverseMat4(t);const s=math.transformVec3(t,this._cameraOffset),r=math.vec3();if(math.subVec3(e.eye,i,r),math.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=math.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=math.normalizeVec3(math.subVec3(e.look,e.eye,tempVec3a$v)),i=math.cross3Vec3(t,e.worldUp,tempVec3b$2);return math.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}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,this._polar+=.01*r,this._polar=math.clamp(this._polar,.001,Math.PI-.001);const o=[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=o[1];o[1]=o[2],o[2]=e}const a=math.lenVec3(math.subVec3(i.look,i.eye,math.vec3())),n=this.getPivotPos();math.addVec3(o,n);let l=math.lookAtMat4v(o,n,i.worldUp);l=math.inverseMat4(l);const h=math.transformVec3(l,this._cameraOffset);l[12]-=h[0],l[13]-=h[1],l[14]-=h[2];const c=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],math.subVec3(i.eye,math.mulVec3Scalar(c,a),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible",this._shown=!0,this._hideTimeout=window.setTimeout(()=>{this.hidePivot()},1e3)))}hidePivot(){this._shown&&(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class PickController{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.pickCursorPos=math.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;this.picked=!1,this.pickedSurface=!1,this._needFireEvents=!1;const e=this._cameraControl.hasSubs("hoverSurface");if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const t=this.pickResult.canvasPos;if(t[0]===this.pickCursorPos[0]&&t[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}if(this.schedulePickEntity&&this.pickResult){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!0,canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(this._needFireEvents){if(this.picked&&this.pickResult&&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=!1}}destroy(){this._scene.off(this._onTick)}}const canvasPos=math.vec2(),getCanvasPosFromEvent=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 MousePanRotateDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let a,n,l=0,h=0,c=0,d=0;this._down=!1;let u=!1;const p=math.vec3();let m=!0;const _=this._scene.canvas.canvas,f=[];document.addEventListener("keydown",this._documentKeyDownHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;f[r]=!0})),document.addEventListener("keyup",this._documentKeyUpHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;f[r]=!1})),_.addEventListener("mousedown",this._mouseDownHandler=(t=>{if(i.active&&i.pointerEnabled)switch(this._down=!0,t.which){case 1:f[e.input.KEY_SHIFT]||i.planView?(_.style.cursor="move",l=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult?(u=!0,p.set(o.pickResult.worldPos)):u=!1):(_.style.cursor="move",l=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1]);break;case 2:a=!0,i.panRightClick||(_.style.cursor="move",l=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1]);break;case 3:n=!0,i.panRightClick&&(_.style.cursor="move",l=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult?(u=!0,p.set(o.pickResult.worldPos)):u=!1)}})),_.addEventListener("mousemove",this._mouseMoveHandler=(t=>{if(!i.active||!i.pointerEnabled)return;if(!s.mouseover)return;if(r.inputFromMouse=!0,m=!0,!this._down)return;const o=e.canvas.boundary,c=o[2]-o[0],d=o[3]-o[1],_=s.pointerCanvasPos[0],g=s.pointerCanvasPos[1];if(f[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&n){const t=_-l,i=g-h,s=e.camera;if("perspective"===s.projection){const o=Math.abs(u?math.lenVec3(math.subVec3(p,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/d,r.panDeltaY+=1.5*i*o/d}else r.panDeltaX+=.5*s.ortho.scale*(t/d),r.panDeltaY+=.5*s.ortho.scale*(i/d)}else i.planView||(i.firstPerson?(r.rotateDeltaY-=(_-l)/c*i.dragRotationRate/2,r.rotateDeltaX+=(g-h)/d*(i.dragRotationRate/4)):(r.rotateDeltaY-=(_-l)/c*i.dragRotationRate,r.rotateDeltaX+=(g-h)/d*i.dragRotationRate));l=_,h=g})),document.addEventListener("mouseup",this._documentMouseUpHandler=(e=>{if(i.active&&i.pointerEnabled){switch(e.which){case 1:break;case 2:a=!1;break;case 3:n=!1}this._down=!1}})),_.addEventListener("mouseup",this._mouseUpHandler=(e=>{if(i.active&&i.pointerEnabled){switch(e.which){case 3:getCanvasPosFromEvent(e,canvasPos);const i=canvasPos[0],s=canvasPos[1];Math.abs(i-c)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{canvasPos:canvasPos,event:e},!0)}_.style.removeProperty("cursor")}})),_.addEventListener("mouseenter",this._mouseEnterHandler=(()=>{i.active&&i.pointerEnabled&&(this._down=!1)})),_.addEventListener("mouseleave",this._mouseLeaveHandler=(()=>{i.active&&i.pointerEnabled&&(r.panDeltaX=0,r.panDeltaY=0,r.rotateDeltaX=0,r.rotateDeltaY=0,this._down=!1)}));let g=null;_.addEventListener("wheel",this._mouseWheelHandler=(e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==g?t-g:0;g=t,o>.05&&(o=.05),o<1/60&&(o=1/60);const a=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===a)return;const n=a/Math.abs(a);r.dollyDelta+=-n*o*i.mouseWheelDollyRate,m&&(s.followPointerDirty=!0,m=!1),e.preventDefault()}))}reset(){this._down=!1}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mousemove",this._mouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const center=math.vec3(),tempVec3a$w=math.vec3(),tempVec3b$3=math.vec3(),tempVec3c$2=math.vec3(),tempVec3d$1=math.vec3(),tempCameraTarget={eye:math.vec3(),look:math.vec3(),up:math.vec3()};class KeyboardAxisViewHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.cameraControl,a=e.camera;e.input.on("keydown",this._documentKeyDownHandler=(r=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=o._isKeyDownForAction(o.AXIS_VIEW_RIGHT),l=o._isKeyDownForAction(o.AXIS_VIEW_BACK),h=o._isKeyDownForAction(o.AXIS_VIEW_LEFT),c=o._isKeyDownForAction(o.AXIS_VIEW_FRONT),d=o._isKeyDownForAction(o.AXIS_VIEW_TOP),u=o._isKeyDownForAction(o.AXIS_VIEW_BOTTOM);if(!(n||l||h||c||d||u))return;const p=e.aabb,m=math.getAABB3Diag(p);math.getAABB3Center(p,center);const _=Math.abs(m/Math.tan(t.cameraFlight.fitFOV*math.DEGTORAD)),f=1.1*m;tempCameraTarget.orthoScale=f,n?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldRight,_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp)):l?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldForward,_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp)):h?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldRight,-_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp)):c?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldForward,-_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp)):d?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldUp,_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(math.normalizeVec3(math.mulVec3Scalar(a.worldForward,1,tempVec3b$3),tempVec3c$2))):u&&(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldUp,-_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(math.normalizeVec3(math.mulVec3Scalar(a.worldForward,-1,tempVec3b$3)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(center),t.cameraFlight.duration>0?t.cameraFlight.flyTo(tempCameraTarget,()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()}):(t.cameraFlight.jumpTo(tempCameraTarget),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){document.removeEventListener("keydown",this._documentKeyDownHandler)}}class MousePickHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,h=!1;const c=this._scene.canvas.canvas,d=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;math.subVec3(i.eye,i.look,[]);t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};c.addEventListener("mousemove",this._canvasMouseMoveHandler=(t=>{if(!i.active||!i.pointerEnabled)return;if(l||h)return;const r=n.hasSubs("hover"),a=n.hasSubs("hoverOut"),c=n.hasSubs("hoverOff"),d=n.hasSubs("hoverSurface");if(r||a||c||d)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&n.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),n.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t),n.fire("hover",o.pickResult,!0),o.pickResult.worldPos&&n.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(n.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),n.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)})),c.addEventListener("mousedown",this._canvasMouseDownHandler=(t=>{1===t.which&&(l=!0),3===t.which&&(h=!0),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&&(o.pickResult?(a.setPivotPos(o.pickResult.worldPos),a.startPivot()):(a.setPivotPos(e.camera.look),a.startPivot()))))})),document.addEventListener("mouseup",this._documentMouseUpHandler=(e=>{1===e.which&&(l=!1),3===e.which&&(h=!1)})),c.addEventListener("mouseup",this._canvasMouseUpHandler=(r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(a.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=n.hasSubs("picked"),h=n.hasSubs("pickedNothing"),c=n.hasSubs("pickedSurface"),u=n.hasSubs("doublePicked"),p=n.hasSubs("doublePickedSurface"),m=n.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||m))return(l||h||c)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(n.fire("picked",o.pickResult,!0),o.pickedSurface&&n.fire("pickedSurface",o.pickResult,!0)):n.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks)this._timeout=setTimeout(()=>{o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=c,o.update(),o.pickResult?(n.fire("picked",o.pickResult,!0),o.pickedSurface&&(n.fire("pickedSurface",o.pickResult,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(o.pickResult.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):n.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0},250);else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(n.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(d(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=math.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(n.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(d(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=math.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 KeyboardPanRotateDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=e.input,a=[],n=e.canvas.canvas;t.pickController;let l=!0;document.addEventListener("mousemove",this._documentMouseMoveHandler=(()=>{l=!0})),document.addEventListener("keydown",this._documentKeyDownHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;a[r]=!0,r===o.KEY_SHIFT&&(n.style.cursor="move")})),document.addEventListener("keyup",this._documentKeyUpHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;a[r]=!1,r===o.KEY_SHIFT&&(n.style.cursor="default")})),this._onTick=e.on("tick",n=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const h=t.cameraControl,c=n.deltaTime/1e3;if(!i.planView){const e=h._isKeyDownForAction(h.ROTATE_Y_POS,a),s=h._isKeyDownForAction(h.ROTATE_Y_NEG,a),o=h._isKeyDownForAction(h.ROTATE_X_POS,a),n=h._isKeyDownForAction(h.ROTATE_X_NEG,a),l=c*i.keyboardRotationRate;(e||s||o||n)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:n&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){const e=h._isKeyDownForAction(h.DOLLY_BACKWARDS,a),o=h._isKeyDownForAction(h.DOLLY_FORWARDS,a);if(e||o){const a=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=a:e&&(r.dollyDelta+=a),l&&(s.followPointerDirty=!0,l=!1)}}const d=h._isKeyDownForAction(h.PAN_FORWARDS,a),u=h._isKeyDownForAction(h.PAN_BACKWARDS,a),p=h._isKeyDownForAction(h.PAN_LEFT,a),m=h._isKeyDownForAction(h.PAN_RIGHT,a),_=h._isKeyDownForAction(h.PAN_UP,a),f=h._isKeyDownForAction(h.PAN_DOWN,a),g=(a[o.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(d||u||p||m||_||f)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),f?r.panDeltaY+=g:_&&(r.panDeltaY+=-g),m?r.panDeltaX+=-g:p&&(r.panDeltaX+=g),u?r.panDeltaZ+=g:d&&(r.panDeltaZ+=-g))})}reset(){}destroy(){this._scene.off(this._onTick),document.removeEventListener("mousemove",this._documentMouseMoveHandler),document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler)}}const SCALE_DOLLY_EACH_FRAME=1,EPSILON=.001,tempVec3$a=math.vec3();class CameraUpdater{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,a=t.pickController,n=t.pivotController,l=t.panController;let h=SCALE_DOLLY_EACH_FRAME,c=1;this._onTick=e.on("tick",t=>{if(!i.active||!i.pointerEnabled)return;let d="default";if(Math.abs(r.dollyDelta){s.mouseover=!0})),o.addEventListener("mouseleave",this._mouseLeaveHandler=(()=>{s.mouseover=!1,o.style.cursor="default"})),o.addEventListener("mousemove",this._mouseMoveHandler=(e=>{getCanvasPosFromEvent$1(e,s.pointerCanvasPos)})),o.addEventListener("mousedown",this._mouseDownHandler=(e=>{i.active&&i.pointerEnabled&&(getCanvasPosFromEvent$1(e,s.pointerCanvasPos),s.mouseover=!0)})),o.addEventListener("mouseup",this._mouseUpHandler=(e=>{i.active&&i.pointerEnabled}))}reset(){}destroy(){const e=this._scene.canvas.canvas;e.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 getCanvasPosFromEvent$1(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 TouchPanRotateAndDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=math.vec2();let l=-1;const h=[];let c=0;const d=math.vec2(),u=(math.vec2(),this._scene.canvas.canvas);let p=!1;this._onTick=e.on("tick",()=>{p=!1}),u.addEventListener("touchstart",this._canvasTouchStartHandler=(e=>{if(!i.active||!i.pointerEnabled)return;const t=e.touches,r=e.changedTouches;if(s.touchStartTime=Date.now(),1===t.length&&1===r.length?(l=s.touchStartTime,n[0]=t[0].pageX,n[1]=t[0].pageY,i.followPointer&&(o.pickCursorPos=n,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(a.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&a.startPivot()&&a.showPivot()):!i.firstPerson&&a.startPivot()&&a.showPivot()))):l=-1,2===t.length){const e=t[0],i=t[1],s=math.geometricMeanVec2([e.pageX,e.pageY],[i.pageX,i.pageY]);o.pickCursorPos=s,o.schedulePickSurface=!0,o.update()}for(;h.length{if(!i.active||!i.pointerEnabled)return;if(p)return;p=!0;const a=e.canvas.boundary,n=a[2]-a[0],l=a[3]-a[1],u=t.touches;if(t.touches.length===c){if(1===c){const t=u[0];if(i.planView){math.subVec2([t.pageX,t.pageY],h[0],d);const s=d[0],o=d[1],a=e.camera;if("perspective"===a.projection){const t=Math.abs(e.camera.eyeLookDist)*Math.tan(a.perspective.fov/2*Math.PI/180);r.panDeltaX+=s*t/l*i.touchPanRate,r.panDeltaY+=o*t/l*i.touchPanRate}else r.panDeltaX+=.5*a.ortho.scale*(s/l)*i.touchPanRate,r.panDeltaY+=.5*a.ortho.scale*(o/l)*i.touchPanRate}else r.rotateDeltaY-=(t.pageX-h[0][0])/n*i.dragRotationRate/2,r.rotateDeltaX+=(t.pageY-h[0][1])/l*(i.dragRotationRate/4)}else if(2===c){const t=u[0],a=u[1],n=math.geometricMeanVec2(h[0],h[1]),c=math.geometricMeanVec2([t.pageX,t.pageY],[a.pageX,a.pageY]),d=math.vec2();math.subVec2(n,c,d);const p=d[0],m=d[1],_=e.camera;if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(math.lenVec3(math.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=p*s/l*i.touchPanRate,r.panDeltaY-=m*s/l*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(p/l)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/l)*i.touchPanRate;const f=math.distVec2([t.pageX,t.pageY],[a.pageX,a.pageY]),g=math.distVec2(h[0],h[1]);r.dollyDelta=(g-f)*i.touchDollyRate,s.pointerCanvasPos=c}for(let e=0;e{e.preventDefault()}),this._configs={tapInterval:150,doubleTapInterval:325,tapDistanceThreshold:4,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!1,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.05,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.06},this._states={pointerCanvasPos:math.vec2(),mouseover:!1,inputFromMouse:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:math.vec2(),tapStartTime:-1,lastTapTime:-1},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new PickController(this,this._configs),pivotController:new PivotController(i),panController:new PanController(this.scene),cameraFlight:new CameraFlightAnimation(this,{duration:.5})},this._handlers=[new MouseMiscHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new TouchPanRotateAndDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new MousePanRotateDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new KeyboardAxisViewHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new MousePickHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new KeyboardPanRotateDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new CameraUpdater(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",utils.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];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]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e{delete i[e.id];const t=s[e.type];t&&t[e.id]&&(delete t[e.id],0==--this._typeCounts[e.type]&&(delete this._typeCounts[e.type],delete s[e.type]));const o=e.children;if(o)for(let e=0,t=o.length;e0?arrayToMap(t):null,a=i&&i.length>0?arrayToMap(i):null;return function e(t){if(!t)return;var i=!0;a&&a[t.type]?i=!1:o&&!o[t.type]&&(i=!1),i&&s.push(t.id);const r=t.children;if(r)for(var n=0,l=r.length;nd.has(e.id)||p.has(e.id)||u.has(e.id)).reduce((e,i)=>{let s,r=colorizeToRGB(i.colorize);return i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,r=(s=Math.round(255*s).toString(16).padStart(2,"0"))+r):d.has(i.id)&&(r=(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"))+r),e[r]||(e[r]=[]),e[r].push({ifc_guid:i.id,originating_system:this.originatingSystem}),e},{}),_=Object.entries(m).map(([e,t])=>({color:e,components:t}));o.components.coloring=_;const f=t.objectIds,g=t.visibleObjects,v=t.visibleObjectIds,b=f.filter(e=>!g[e]),y=t.selectedObjectIds;return e.defaultInvisible||v.lengththis._objectIdToComponent(e)),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=b.map(e=>this._objectIdToComponent(e)),o.components.visibility.default_visibility=!0),o.components.selection=y.map(e=>this._objectIdToComponent(e)),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_objectIdToComponent(e){return{ifc_guid:e,originating_system:this.originatingSystem,authoring_tool_id:this.authoringTool}}setViewpoint(e,t={}){if(!e)return;const i=this.viewer,s=i.scene,r=s.camera,o=!1!==t.rayCast,a=!1!==t.immediate,n=!1!==t.reset,l=!!t.updateCompositeObjects,h=s.realWorldOffset,c=!0===t.reverseClippingPlanes;if(s.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.forEach(function(e){let t=xyzObjectToArray(e.location,tempVec3$b),i=xyzObjectToArray(e.direction,tempVec3$b);c&&math.negateVec3(i),math.subVec3(t,h),r.yUp&&(t=ZToY(t),i=ZToY(i)),new SectionPlane(s,{pos:t,dir:i})}),n&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach(e=>{const t=i.scene.objects[e.ifc_guid];t?t.visible=!1:s.setObjectsVisible(l?i.metaScene.getObjectIDsInSubtree(e.ifc_guid):e.ifc_guid,!1)})):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach(e=>{const t=i.scene.objects[e.ifc_guid];t?t.visible=!0:s.setObjectsVisible(l?i.metaScene.getObjectIDsInSubtree(e.ifc_guid):e.ifc_guid,!0)}));const t=e.components.visibility.view_setup_hints;t&&(!1===t.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===t.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!1),t.space_boundaries_visible)}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),Object.keys(s.models).forEach(()=>{e.components.selection.forEach(e=>s.setObjectsSelected(l?i.metaScene.getObjectIDsInSubtree(e.ifc_guid):e.ifc_guid,!0))})),e.components.coloring&&e.components.coloring.forEach(e=>{let t=e.components.map(e=>e.ifc_guid),i=e.color;if(8===i.length){let e=parseInt(i.substring(0,2),16)/256;i=i.substring(2),s.setObjectsOpacity(t,e)}let r=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];s.setObjectsColorized(t,r)})}if(e.perspective_camera||e.orthogonal_camera){let n,l,c,d;if(e.perspective_camera?(n=xyzObjectToArray(e.perspective_camera.camera_view_point,tempVec3$b),l=xyzObjectToArray(e.perspective_camera.camera_direction,tempVec3$b),c=xyzObjectToArray(e.perspective_camera.camera_up_vector,tempVec3$b),r.perspective.fov=e.perspective_camera.field_of_view,d="perspective"):(n=xyzObjectToArray(e.orthogonal_camera.camera_view_point,tempVec3$b),l=xyzObjectToArray(e.orthogonal_camera.camera_direction,tempVec3$b),c=xyzObjectToArray(e.orthogonal_camera.camera_up_vector,tempVec3$b),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,d="ortho"),math.subVec3(n,h),r.yUp&&(n=ZToY(n),l=ZToY(l),c=ZToY(c)),o){const e=s.pick({pickSurface:!0,origin:n,direction:l});l=e?e.worldPos:math.addVec3(n,l,tempVec3$b)}else l=math.addVec3(n,l,tempVec3$b);a?(r.eye=n,r.look=l,r.up=c,r.projection=d):i.cameraFlight.flyTo({eye:n,look:l,up:c,duration:t.duration,projection:d})}}destroy(){super.destroy()}}function xyzArrayToObject(e){return{x:e[0],y:e[1],z:e[2]}}function xyzObjectToArray(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function YToZ(e){return new Float64Array([e[0],-e[2],e[1]])}function ZToY(e){return new Float64Array([e[0],e[2],-e[1]])}function colorizeToRGB(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0")}const tempVec3a$x=math.vec3();class ThreeDMode extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";this._buttonElement=t.buttonElement,this._cameraControlNavModeMediator=t.cameraControlNavModeMediator,this._active=!1,this.on("enabled",e=>{e?this._buttonElement.classList.remove("disabled"):this._buttonElement.classList.add("disabled")}),this._buttonElement.addEventListener("click",e=>{this.setActive(!this.getActive(),()=>{}),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!0,()=>{})})}setActive(e,t){this._active!==e?(this._active=e,e?(this._buttonElement.classList.add("active"),t?this._enterThreeDMode(()=>{this.fire("active",this._active),t()}):(this._enterThreeDMode(),this.fire("active",this._active))):(this._buttonElement.classList.remove("active"),t?this._exitThreeDMode(()=>{this.fire("active",this._active),t()}):(this._exitThreeDMode(),this.fire("active",this._active)))):t&&t()}_enterThreeDMode(e){const t=this.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds),r=math.getAABB3Diag(s),o=math.getAABB3Center(s,tempVec3a$x),a=Math.abs(r/Math.tan(32.5)),n=i.camera,l=n.yUp?[-1,-1,-1]:[1,1,1],h=n.yUp?[-1,1,-1]:[-1,1,1];t.cameraControl.pivotPos=o,this.bimViewer._navCubeMode.setActive(!0),this.bimViewer._firstPersonMode.setEnabled(!0),this._cameraControlNavModeMediator.setThreeDModeActive(!0),this.bimViewer._sectionTool.setEnabled(!0),e?t.cameraFlight.flyTo({look:o,eye:[o[0]-a*l[0],o[1]-a*l[1],o[2]-a*l[2]],up:h,orthoScale:1.3*r,duration:1},()=>{e()}):t.cameraFlight.jumpTo({look:o,eye:[o[0]-a*l[0],o[1]-a*l[1],o[2]-a*l[2]],up:h,orthoScale:1.3*r})}_exitThreeDMode(e){const t=this.viewer,i=t.scene,s=i.camera,r=i.getAABB(i.visibleObjectIds),o=math.getAABB3Center(r),a=math.getAABB3Diag(r),n=Math.abs(a/Math.tan(45*math.DEGTORAD)),l=1.3*a,h=tempVec3a$x;h[0]=o[0]+s.worldUp[0]*n,h[1]=o[1]+s.worldUp[1]*n,h[2]=o[2]+s.worldUp[2]*n;const c=math.mulVec3Scalar(s.worldForward,-1,[]);this.bimViewer._sectionTool.setActive(!1),this.bimViewer._sectionTool.clear(),this.bimViewer._firstPersonMode.setEnabled(!1),this.bimViewer._sectionTool.setEnabled(!1),this._cameraControlNavModeMediator.setThreeDModeActive(!1),e?t.cameraFlight.flyTo({eye:h,look:o,up:c,orthoScale:l},()=>{this.bimViewer._navCubeMode.setActive(!1)}):(t.cameraFlight.jumpTo({eye:h,look:o,up:c,orthoScale:l}),this.bimViewer._navCubeMode.setActive(!1))}}class ObjectContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"View Fit",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity;t.cameraFlight.flyTo({aabb:s.aabb,duration:.5},()=>{setTimeout(function(){i.setObjectsHighlighted(i.highlightedObjectIds,!1)},500)}),t.cameraControl.pivotPos=math.getAABB3Center(s.aabb)}},{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}},{title:"Show in Tree",doAction:function(e){const t=e.entity.id;e.showObjectInExplorers(t)}}],[{title:"Hide",getEnabled:function(e){return e.entity.visible},doAction:function(e){e.entity.visible=!1}},{title:"Hide Others",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity,r=t.metaScene.metaObjects[s.id];r&&(i.setObjectsVisible(i.visibleObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),r.withMetaObjectsInSubtree(e=>{const t=i.objects[e.id];t&&(t.visible=!0)}))}},{title:"Hide All",getEnabled:function(e){return e.viewer.scene.numVisibleObjects>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}},{title:"Show All",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray",getEnabled:function(e){return!e.entity.xrayed},doAction:function(e){const t=e.entity;t.xrayed=!0,t.pickable=!1}},{title:"X-Ray Others",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity,r=t.metaScene.metaObjects[s.id];r&&(i.setObjectsVisible(i.objectIds,!0),i.setObjectsXRayed(i.objectIds,!0),i.setObjectsPickable(i.objectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),r.withMetaObjectsInSubtree(e=>{const t=i.objects[e.id];t&&(t.xrayed=!1,t.pickable=!0)}))}},{title:"X-Ray All",getEnabled:function(e){const t=e.viewer.scene;return t.numXRayedObjects0},doAction:function(e){const t=e.viewer.scene,i=t.xrayedObjectIds;t.setObjectsPickable(i,!0),t.setObjectsXRayed(i,!1)}}],[{title:"Select",getEnabled:function(e){return!e.entity.selected},doAction:function(e){e.entity.selected=!0}},{title:"Undo Select",getEnabled:function(e){return e.entity.selected},doAction:function(e){e.entity.selected=!1}},{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class CanvasContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"Hide All",getEnabled:function(e){return e.viewer.scene.numVisibleObjects>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}},{title:"Show all",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}}],[{title:"X-Ray All",getEnabled:function(e){const t=e.viewer.scene;return t.numXRayedObjects0},doAction:function(e){const t=e.viewer.scene.xrayedObjectIds;e.viewer.scene.setObjectsPickable(t,!0),e.viewer.scene.setObjectsXRayed(t,!1)}}],[{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Reset View",doAction:function(e){e.bimViewer.resetView()}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class OrthoMode extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";this._buttonElement=t.buttonElement,this.on("enabled",e=>{e?this._buttonElement.classList.remove("disabled"):this._buttonElement.classList.add("disabled")}),this._buttonElement.addEventListener("click",e=>{this.setActive(!this.getActive()),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)})}setActive(e,t){this._active!==e?(this._active=e,e?(this._buttonElement.classList.add("active"),t?this._enterOrthoMode(()=>{this.fire("active",this._active),t()}):(this._enterOrthoMode(),this.fire("active",this._active))):(this._buttonElement.classList.remove("active"),t?this._exitOrthoMode(()=>{this.fire("active",this._active),t()}):(this._exitOrthoMode(),this.fire("active",this._active)))):t&&t()}_enterOrthoMode(e){this.viewer.cameraFlight.flyTo({projection:"ortho",duration:.5},e)}_exitOrthoMode(e){this.viewer.cameraFlight.flyTo({projection:"perspective",duration:.5},e)}}function createExplorerTemplate(e){return'
\n
\n Models\n
\n
\n \n '+(e.enableEditModels?'':"")+'
\n
\n
\n
\n
\n Objects\n
\n
\n \n \n
\n
\n
\n
\n
\n Classes\n
\n
\n \n \n
\n
\n
\n
\n
\n Storeys\n
\n
\n \n \n
\n
\n
\n
\n
'}const toolbarTemplate='
\n \x3c!-- Reset button --\x3e\n
\n \n
\n
\n \x3c!-- 3D Mode button --\x3e\n \n \x3c!-- Perspective/Ortho Mode button --\x3e\n \n \x3c!-- Fit button --\x3e\n \n \x3c!-- First Person mode button --\x3e\n \n
\n \x3c!-- Tools button group --\x3e\n
\n \x3c!-- Hide tool button --\x3e\n \n \x3c!-- Select tool button --\x3e\n \n \x3c!-- Query tool button --\x3e\n \n \x3c!-- section tool button --\x3e\n \n
\n\n
';function initTabs(e){const t="xeokit-tab",i="active";function s(e){let s=e.parentNode.querySelectorAll("."+t);for(let t=0;t{e.preventDefault()}),r.oncontextmenu=(e=>{e.preventDefault()}),o.oncontextmenu=(e=>{e.preventDefault()});const l=new Viewer({canvasElement:i,transparent:!0});super(null,t,e,l),this._configs={},this.viewer=l,this._customizeViewer(),this._initCanvasContextMenus(),this._initConfigs(),this._enableAddModels=!!t.enableEditModels,s.innerHTML=createExplorerTemplate(t),r.innerHTML=toolbarTemplate,this._explorerElement=s,initTabs(s),this._modelsExplorer=new ModelsExplorer(this,{modelsTabElement:s.querySelector(".xeokit-modelsTab"),loadModelsButtonElement:s.querySelector(".xeokit-loadAllModels"),unloadModelsButtonElement:s.querySelector(".xeokit-unloadAllModels"),addModelButtonElement:s.querySelector(".xeokit-addModel"),modelsElement:s.querySelector(".xeokit-models"),enableEditModels:this._enableAddModels}),this._objectsExplorer=new ObjectsExplorer(this,{objectsTabElement:s.querySelector(".xeokit-objectsTab"),showAllObjectsButtonElement:s.querySelector(".xeokit-showAllObjects"),hideAllObjectsButtonElement:s.querySelector(".xeokit-hideAllObjects"),objectsElement:s.querySelector(".xeokit-objects")}),this._classesExplorer=new ClassesExplorer(this,{classesTabElement:s.querySelector(".xeokit-classesTab"),showAllClassesButtonElement:s.querySelector(".xeokit-showAllClasses"),hideAllClassesButtonElement:s.querySelector(".xeokit-hideAllClasses"),classesElement:s.querySelector(".xeokit-classes")}),this._storeysExplorer=new StoreysExplorer(this,{storeysTabElement:s.querySelector(".xeokit-storeysTab"),showAllStoreysButtonElement:s.querySelector(".xeokit-showAllStoreys"),hideAllStoreysButtonElement:s.querySelector(".xeokit-hideAllStoreys"),storeysElement:s.querySelector(".xeokit-storeys")}),this._resetAction=new ResetAction(this,{buttonElement:r.querySelector(".xeokit-reset"),active:!1}),this._fitAction=new FitAction(this,{buttonElement:r.querySelector(".xeokit-fit"),active:!1});const h=new function(e){let t=!1;this.setThreeDModeActive=(i=>{i?(e._firstPersonMode.setActive(!1),e.viewer.cameraControl.navMode="orbit"):(e._firstPersonMode.setActive(!1),e.viewer.cameraControl.navMode="planView"),t=i}),this.setFirstPersonModeActive=(i=>{e.viewer.cameraControl.navMode=i?"firstPerson":t?"orbit":"planView"})}(this);this._threeDMode=new ThreeDMode(this,{buttonElement:r.querySelector(".xeokit-threeD"),cameraControlNavModeMediator:h,active:!1}),this._orthoMode=new OrthoMode(this,{buttonElement:r.querySelector(".xeokit-ortho"),active:!1}),this._firstPersonMode=new FirstPersonMode(this,{buttonElement:r.querySelector(".xeokit-firstPerson"),cameraControlNavModeMediator:h,active:!1}),this._hideTool=new HideTool(this,{buttonElement:r.querySelector(".xeokit-hide"),active:!1}),this._selectionTool=new SelectionTool(this,{buttonElement:r.querySelector(".xeokit-select"),active:!1}),this._queryTool=new QueryTool(this,{buttonElement:r.querySelector(".xeokit-query"),queryInfoPanelElement:a,active:!1}),this._sectionTool=new SectionTool(this,{buttonElement:r.querySelector(".xeokit-section"),counterElement:r.querySelector(".xeokit-section-counter"),menuButtonElement:r.querySelector(".xeokit-section-menu-button"),menuButtonArrowElement:r.querySelector(".xeokit-section-menu-button-arrow"),active:!1}),this._navCubeMode=new NavCubeMode(this,{navCubeCanvasElement:o,active:!0}),this._busyModal=new BusyModal(this,{busyModalBackdropElement:n}),this._threeDMode.setActive(!0),this._firstPersonMode.setActive(!1),this._navCubeMode.setActive(!0),this._modelsExplorer.on("modelLoaded",e=>{this._modelsExplorer.getNumModelsLoaded()>0&&this.setControlsEnabled(!0),this.fire("modelLoaded",e)}),this._modelsExplorer.on("modelUnloaded",e=>{0===this._modelsExplorer.getNumModelsLoaded()&&(this.setControlsEnabled(!1),this.openTab("models")),this.fire("modelUnloaded",e)}),this._queryTool.on("queryPicked",e=>{this.fire("queryPicked",e)}),this._queryTool.on("queryNotPicked",()=>{this.fire("queryNotPicked",!0)}),this._resetAction.on("reset",()=>{this.fire("reset",!0)}),this._mutexActivation([this._queryTool,this._hideTool,this._selectionTool,this._sectionTool]),s.querySelector(".xeokit-showAllObjects").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllObjects").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-showAllClasses").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllClasses").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-showAllStoreys").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllStoreys").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-loadAllModels").addEventListener("click",e=>{this.setControlsEnabled(!1),this.loadAllModels(),e.preventDefault()}),s.querySelector(".xeokit-unloadAllModels").addEventListener("click",e=>{this.setControlsEnabled(!1),this._modelsExplorer.unloadAllModels(),e.preventDefault()}),this._enableAddModels&&s.querySelector(".xeokit-addModel").addEventListener("click",e=>{this.fire("addModel",{}),e.preventDefault()}),this._bcfViewpointsPlugin=new BCFViewpointsPlugin(this.viewer,{})}_customizeViewer(){const e=this.viewer.scene;e.xrayMaterial.fill=!1,e.xrayMaterial.fillAlpha=.1,e.xrayMaterial.fillColor=[0,0,0],e.xrayMaterial.edges=!0,e.xrayMaterial.edgeAlpha=.3,e.xrayMaterial.edgeColor=[0,0,0],e.highlightMaterial.edges=!0,e.highlightMaterial.edgeColor=[.5,.5,0],e.highlightMaterial.edgeAlpha=.9,e.highlightMaterial.fill=!0,e.highlightMaterial.fillAlpha=.1,e.highlightMaterial.fillColor=[1,0,0],e.clearLights(),new AmbientLight(e,{color:[.3,.3,.3],intensity:1}),new DirLight(e,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"world"}),new DirLight(e,{dir:[-.8,-.4,.4],color:[1,1,1],intensity:1,space:"world"}),new DirLight(e,{dir:[.2,-.8,.8],color:[.6,.6,.6],intensity:1,space:"world"}),this.viewer.cameraControl.panRightClick=!0,this.viewer.cameraControl.followPointer=!0,this.viewer.cameraControl.doublePickFlyTo=!0,this.viewer.cameraControl.keyboardDollyRate=100,this.viewer.cameraControl.mouseWheelDollyRate=100,this.viewer.cameraControl.dollyInertia=0,this.viewer.cameraControl.dollyMinSpeed=.01,this.viewer.cameraControl.dollyProximityThreshold=30;const t=document.createRange().createContextualFragment("
").firstChild;document.body.appendChild(t),this.viewer.cameraControl.pivotElement=t,e.camera.perspective.near=.01,e.camera.perspective.far=3e3,e.camera.ortho.near=.01,e.camera.ortho.far=3e3;const i=e.sao;i.enabled=!1,i.bias=.5,i.intensity=.2,i.scale=1200,i.kernelRadius=100;var s=200,r=!1;e.camera.on("matrix",()=>{if(this._configs.saoInteractive)return;const t=this._configs.saoInteractiveDelay;s=null!==t&&void 0!==t?this._configs.saoInteractiveDelay:200,r&&(e.sao.enabled=!1,r=!1)}),e.on("tick",t=>{this._configs.saoInteractive?r||(e.sao.enabled=!!this._configs.saoEnabled,r=!0):r||(s-=t.deltaTime)<=0&&(r||(e.sao.enabled=!!this._configs.saoEnabled,r=!0))})}_initCanvasContextMenus(){this._canvasContextMenu=new CanvasContextMenu,this._objectContextMenu=new ObjectContextMenu,this.viewer.cameraControl.on("rightClick",e=>{const t=e.event,i=this.viewer.scene.pick({canvasPos:[t.offsetX,t.offsetY]});i&&i.entity.isObject?(this._canvasContextMenu.hide(),this._objectContextMenu.context={viewer:this.viewer,bimViewer:this,showObjectInExplorers:e=>{const t=this.getOpenTab();"objects"!==t&&"classes"!==t&&"storeys"!==t&&this.openTab("objects"),this.showObjectInExplorers(e)},entity:i.entity},this._objectContextMenu.show(t.pageX,t.pageY)):(this._objectContextMenu.hide(),this._canvasContextMenu.context={viewer:this.viewer,bimViewer:this},this._canvasContextMenu.show(t.pageX,t.pageY))})}_initConfigs(){this.setConfigs({cameraNear:"0.05",cameraFar:"3000.0",saoEnabled:"false",saoBias:"0.5",saoIntensity:"0.5",saoScale:"1200.0",saoKernelRadius:"100",xrayContext:!0,backgroundColor:[1,1,1],saoInteractive:!0,saoInteractiveDelay:200,objectColorSource:"model"})}setConfigs(e){for(let t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setConfig(t,i)}}setConfig(e,t){function i(e){return!0===e||"true"===e}try{switch(e){case"backgroundColor":const r=t;this.setBackgroundColor(r),this._configs[e]=r;break;case"cameraNear":const o=parseFloat(t);this.viewer.scene.camera.perspective.near=o,this.viewer.scene.camera.ortho.near=o,this._configs[e]=o;break;case"cameraFar":const a=parseFloat(t);this.viewer.scene.camera.perspective.far=a,this.viewer.scene.camera.ortho.far=a,this._configs[e]=a;break;case"saoEnabled":this.viewer.scene.sao.enabled=this._configs[e]=i(t);break;case"saoBias":this.viewer.scene.sao.bias=parseFloat(t);break;case"saoIntensity":this.viewer.scene.sao.intensity=parseFloat(t);break;case"saoScale":this.viewer.scene.sao.scale=this._configs[e]=parseFloat(t);break;case"saoKernelRadius":this.viewer.scene.sao.kernelRadius=this._configs[e]=parseFloat(t);break;case"saoBlur":this.viewer.scene.sao.blur=this._configs[e]=i(t);break;case"viewFitFOV":this.viewer.cameraFlight.fitFOV=this._configs[e]=parseFloat(t);break;case"viewFitDuration":this.viewer.cameraFlight.duration=this._configs[e]=parseFloat(t);break;case"perspectiveFOV":this.viewer.camera.perspective.fov=this._configs[e]=parseFloat(t);break;case"excludeUnclassifiedObjects":this._configs[e]=i(t);break;case"objectColorSource":this.setObjectColorSource(t),this._configs[e]=t;break;case"xrayContext":this._configs[e]=t;break;case"saoInteractive":this._configs.saoInteractive=i(t);break;case"saoInteractiveDelay":var s=parseFloat(t);s<0&&(this.error("setConfig() - saoInteractiveDelay cannot be less than zero - clamping to zero"),s=0),this._configs.saoInteractiveDelay=parseFloat(t);break;default:this.error("setConfig() - unsupported configuration: '"+e+"'")}}catch(t){this.error("setConfig() - failed to configure '"+e+"': "+t)}}getConfig(e){return this._configs[e]}getProjectsInfo(e,t){e?this.server.getProjects(e,e=>{this.error("getProjectsInfo() - "+e),t&&t(e)}):this.error("getProjectsInfo() - Argument expected: 'done'")}getProjectInfo(e,t,i){e?t?this.server.getProject(e,t,e=>{this.error("getProjectInfo() - "+e),i&&i(e)}):this.error("getProjectInfo() - Argument expected: 'done'"):this.error("getProjectInfo() - Argument expected: projectId")}getObjectInfo(e,t,i,s,r){e?t?i?s?this.server.getObjectInfo(e,t,i,s,e=>{r&&r(e)}):this.error("getProjectInfo() - Argument expected: 'done'"):this.error("getObjectInfo() - Argument expected: objectId"):this.error("getObjectInfo() - Argument expected: modelId"):this.error("getObjectInfo() - Argument expected: projectId")}loadProject(e,t,i){e?this._modelsExplorer.loadProject(e,()=>{t&&t()},e=>{this.error("loadProject() - "+e),i&&i(e)}):this.error("loadProject() - Argument expected: objectId")}unloadProject(){this._modelsExplorer.unloadProject(),this.openTab("models"),this.setControlsEnabled(!1)}getLoadedProjectId(){return this._modelsExplorer.getLoadedProjectId()}getModelIds(){return this._modelsExplorer.getModelIds()}loadModel(e,t,i){e?this._modelsExplorer.loadModel(e,()=>{t&&t()},e=>{this.error("loadModel() - "+e),i&&i(e)}):this.error("loadModel() - Argument expected: modelId")}loadAllModels(e=function(){}){const t=this._modelsExplorer.getModelIds(),i=(e,s)=>{if(e>=t.length)s();else{const r=t[e];this._modelsExplorer.isModelLoaded(r)?i(e+1,s):this._modelsExplorer.loadModel(r,()=>{i(e+1,s)},t=>{this.error("loadAllModels() - "+t),i(e+1,s)})}};i(0,e)}getLoadedModelIds(){return this._modelsExplorer._getLoadedModelIds()}isModelLoaded(e){if(e)return this._modelsExplorer.isModelLoaded(e);this.error("unloadModel() - Argument expected: modelId")}unloadModel(e){e?this._modelsExplorer.unloadModel(e):this.error("unloadModel() - Argument expected: modelId")}unloadAllModels(){this._modelsExplorer.unloadAllModels()}editModel(e){this.fire("editModel",{modelId:e})}deleteModel(e){this.fire("deleteModel",{modelId:e})}addModel(){this.fire("addModel",{})}setBackgroundColor(e){this.viewer.scene.canvas.canvas.style.background="rgba("+255*e[0]+","+255*e[1]+","+255*e[2]+", 1.0)"}setObjectColorSource(e){switch(e){case"model":case"viewer":break;default:return e="model",void this.error("setObjectColorSource() - Unsupported value - accepted values are 'model' and 'viewer' - defaulting to 'model'")}this._objectColorSource=e}getObjectColorSource(){return this._objectColorSource||"model"}setViewerState(e,t=(()=>{})){e.tabOpen&&this.openTab(e.tabOpen),e.expandObjectsTree&&this._objectsExplorer.expandTreeViewToDepth(e.expandObjectsTree),e.expandClassesTree&&this._classesExplorer.expandTreeViewToDepth(e.expandClassesTree),e.expandStoreysTree&&this._storeysExplorer.expandTreeViewToDepth(e.expandStoreysTree),e.setCamera&&this.setCamera(e.setCamera),this._parseSelectedStorey(e,()=>{this._parseThreeDMode(e,()=>{t()})})}_parseSelectedStorey(e,t){e.selectedStorey?(this.selectStorey(e.selectedStorey),t()):t()}_parseThreeDMode(e,t){const i=!1!==e.threeDActive;this.set3DEnabled(i,t)}showObjectInExplorers(e){e?(this._objectsExplorer.showNodeInTreeView(e),this._classesExplorer.showNodeInTreeView(e),this._storeysExplorer.showNodeInTreeView(e)):this.error("showObjectInExplorers() - Argument expected: objectId")}unShowObjectInExplorers(){this._objectsExplorer.unShowNodeInTreeView(),this._classesExplorer.unShowNodeInTreeView(),this._storeysExplorer.unShowNodeInTreeView()}setObjectsVisible(e,t){this._withObjectsInSubtree(e,e=>{e.visible=t})}setAllObjectsVisible(e){e?this.viewer.scene.setObjectsVisible(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsVisible(this.viewer.scene.visibleObjectIds,!1)}setObjectsXRayed(e,t){this._withObjectsInSubtree(e,e=>{e.xrayed=t})}setAllObjectsXRayed(e){e?this.viewer.scene.setObjectsXRayed(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsXRayed(this.viewer.scene.xrayedObjectIds,!1)}setObjectsSelected(e,t){this._withObjectsInSubtree(e,e=>{e.selected=t})}setAllObjectsSelected(e){e?this.viewer.scene.setObjectsSelected(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsSelected(this.viewer.scene.selectedObjectIds,!1)}_withObjectsInSubtree(e,t){if(e)for(let i=0,s=e.length;i{const i=this.viewer.scene.objects[e.id];i&&t(i)})}else this.error("Argument expected: objectIds")}flyToObject(e,t){if(!e)return void this.error("flyToObject() - Argument expected: objectId");const i=this.viewer,s=i.scene,r=[];if(this.viewer.metaScene.withMetaObjectsInSubtree(e,e=>{s.objects[e.id]&&r.push(e.id)}),0===r.length)return this.error("Object not found in viewer: '"+e+"'"),void(t&&t());s.setObjectsVisible(r,!0),s.setObjectsHighlighted(r,!0);const o=s.getAABB(r);i.cameraFlight.flyTo({aabb:o},()=>{t&&t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}),i.cameraControl.pivotPos=math.getAABB3Center(o)}viewFitObjects(e,t){if(!e)return void this.error("flyToObject() - Argument expected: objectIds");const i=this.viewer,s=i.scene,r=[];for(var o=0,a=e.length;o{s.objects[e.id]&&r.push(e.id)})}if(0===r.length)return void(t&&t());s.setObjectsVisible(r,!0),s.setObjectsHighlighted(r,!0);const n=s.getAABB(r);i.cameraFlight.flyTo({aabb:n},()=>{t&&t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}),i.cameraControl.pivotPos=math.getAABB3Center(n)}viewFitAll(e){const t=this.viewer,i=t.scene.getAABB();t.cameraFlight.flyTo({aabb:i},()=>{e&&e()}),t.cameraControl.pivotPos=math.getAABB3Center(i)}jumpToObject(e){if(!e)return void this.error("jumpToObject() - Argument expected: objectId");const t=this.viewer,i=t.scene,s=[];if(this.viewer.metaScene.withMetaObjectsInSubtree(e,e=>{i.objects[e.id]&&s.push(e.id)}),0===s.length)return void this.error("Object not found in viewer: '"+e+"'");i.setObjectsVisible(s,!0);const r=i.getAABB(s);t.cameraFlight.jumpTo({aabb:r}),t.cameraControl.pivotPos=math.getAABB3Center(r)}setCamera(e){const t=this.viewer.scene.camera;e.eye&&(t.eye=e.eye),e.look&&(t.look=e.look),e.up&&(t.up=e.up)}viewFitModels(e,t){if(!e)return void this.error("viewFitModels() - Argument expected: modelIds");const i=this.viewer,s=i.scene,r=math.AABB3();math.collapseAABB3(r);for(var o=0,a=e.length;o{t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}):(i.cameraFlight.jumpTo({aabb:r}),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)),i.cameraControl.pivotPos=math.getAABB3Center(r)}openTab(e){if(!e)return void this.error("openTab() - Argument expected: tabId");let t;switch(e){case"models":t="xeokit-modelsTab";break;case"objects":t="xeokit-objectsTab";break;case"classes":t="xeokit-classesTab";break;case"storeys":t="xeokit-storeysTab";break;default:return void this.error("openTab() - tab not recognized: '"+e+"'")}let i=this._explorerElement.querySelectorAll(".xeokit-tab"),s=this._explorerElement.querySelector("."+t);for(let e=0;e-1}return e(this._explorerElement.querySelector(".xeokit-modelsTab"),"active")?"models":e(this._explorerElement.querySelector(".xeokit-objectsTab"),"active")?"objects":e(this._explorerElement.querySelector(".xeokit-classesTab"),"active")?"classes":e(this._explorerElement.querySelector(".xeokit-storeysTab"),"active")?"storeys":"none"}set3DEnabled(e,t){this._threeDMode.setActive(e,t)}get3DEnabled(){return this._threeDMode.getActive()}setOrthoEnabled(e,t){this._orthoMode.setActive(e,t)}getOrthoEnabled(){return this._orthoMode.getActive()}selectStorey(e,t){const i=this.viewer.metaScene.metaObjects[e];i?"IfcBuildingStorey"===i.type?this._storeysExplorer.selectStorey(e,t):this.error("selectStorey() - Object is not an IfcBuildingStorey: '"+e+"'"):this.error("selectStorey() - Object is not found: '"+e+"'")}saveBCFViewpoint(e){return this._bcfViewpointsPlugin.getViewpoint(e)}loadBCFViewpoint(e,t){e?this._bcfViewpointsPlugin.setViewpoint(e,t):this.error("loadBCFViewpoint() - Argument expected: bcfViewpoint")}resetView(){this._resetAction.reset()}setControlsEnabled(e){this._objectsExplorer.setEnabled(e),this._classesExplorer.setEnabled(e),this._storeysExplorer.setEnabled(e),this._resetAction.setEnabled(e),this._fitAction.setEnabled(e),this._threeDMode.setEnabled(e),this._orthoMode.setEnabled(e),this._firstPersonMode.setEnabled(e),this._queryTool.setEnabled(e),this._hideTool.setEnabled(e),this._selectionTool.setEnabled(e),this._sectionTool.setEnabled(e)}setKeyboardEnabled(e){this.viewer.scene.input.keyboardEnabled=e}getKeyboardEnabled(){return this.viewer.scene.input.keyboardEnabled}clearSections(){this._sectionTool.clear()}flipSections(){this._sectionTool.flipSections()}getNumSections(){return this._sectionTool.getNumSections()}destroy(){this.viewer.destroy(),this._bcfViewpointsPlugin.destroy(),this._canvasContextMenu.destroy(),this._objectContextMenu.destroy()}}export{BIMViewer,Server}; +function xmlToJson(e,t){if(e.nodeType===e.TEXT_NODE){var i=e.nodeValue;if(null===i.match(/^\s+$/))return i}else if(e.nodeType===e.ELEMENT_NODE||e.nodeType===e.DOCUMENT_NODE){var s={type:e.nodeName,children:[]};if(e.nodeType===e.ELEMENT_NODE)for(var r=0;rvoid 0;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)}function loadArraybuffer(e,t,i){var s=e=>void 0;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),s=new Uint8Array(e);for(var a=0;a
Default text
',i.appendChild(this._modal),this._modalVisible=!1,this._modal.style.display="hidden"}show(e){this._modalVisible=!0,this._modal.querySelector(".xeokit-busy-modal-message").innerText=e,this._modal.style.display="block"}hide(){this._modalVisible=!1,this._modal.style.display="none"}destroy(){super.destroy(),this._modal&&(this._modal.parentNode.removeChild(this._modal),this._modal=null)}}const FloatArrayType=Float64Array,tempMat1=new FloatArrayType(16),tempMat2=new FloatArrayType(16),tempVec4=new FloatArrayType(4),math={MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,DEGTORAD:.0174532925,RADTODEG:57.295779513,vec2:e=>new FloatArrayType(e||2),vec3:e=>new FloatArrayType(e||3),vec4:e=>new FloatArrayType(e||4),mat3:e=>new FloatArrayType(e||9),mat3ToMat4:(e,t=new FloatArrayType(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 FloatArrayType(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new Float32Array(2);for(let r=0,o=e.length;r{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(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,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 FloatArrayType(e[0]);for(let i=1;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],a=t[1],n=t[2];return[s*n-r*a,r*o-i*n,i*a-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],a=t[0],n=t[1],l=t[2];return i[0]=r*l-o*n,i[1]=o*a-s*l,i[2]=s*n-r*a,i},sqLenVec4:e=>math.dotVec4(e,e),lenVec4:e=>Math.sqrt(math.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=>math.dotVec3(e,e),sqLenVec2:e=>math.dotVec2(e,e),lenVec3:e=>Math.sqrt(math.sqLenVec3(e)),distVec3:(()=>{const e=new FloatArrayType(3);return(t,i)=>math.lenVec3(math.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(math.sqLenVec2(e)),distVec2:(()=>{const e=new FloatArrayType(2);return(t,i)=>math.lenVec2(math.subVec2(t,i,e))})(),rcpVec3:(e,t)=>math.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/math.lenVec4(e);return math.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/math.lenVec3(e);return math.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/math.lenVec2(e);return math.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=math.dotVec3(e,t)/Math.sqrt(math.sqLenVec3(e)*math.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new FloatArrayType(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=math.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=math.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=math.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({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||new FloatArrayType(3))[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:()=>math.m4s(0),setMat4ToOnes:()=>math.m4s(1),diagonalMat4v:e=>new FloatArrayType([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)=>math.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>math.diagonalMat4c(e,e,e,e),identityMat4:(e=new FloatArrayType(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 FloatArrayType(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)=>math.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],a=e[3],n=e[4],l=e[5],h=e[6],c=e[7],d=e[8],u=e[9],p=e[10],m=e[11],_=e[12],f=e[13],g=e[14],v=e[15],b=t[0],y=t[1],M=t[2],w=t[3],P=t[4],x=t[5],E=t[6],A=t[7],C=t[8],R=t[9],S=t[10],L=t[11],D=t[12],T=t[13],k=t[14],B=t[15];return i[0]=b*s+y*n+M*d+w*_,i[1]=b*r+y*l+M*u+w*f,i[2]=b*o+y*h+M*p+w*g,i[3]=b*a+y*c+M*m+w*v,i[4]=P*s+x*n+E*d+A*_,i[5]=P*r+x*l+E*u+A*f,i[6]=P*o+x*h+E*p+A*g,i[7]=P*a+x*c+E*m+A*v,i[8]=C*s+R*n+S*d+L*_,i[9]=C*r+R*l+S*u+L*f,i[10]=C*o+R*h+S*p+L*g,i[11]=C*a+R*c+S*m+L*v,i[12]=D*s+T*n+k*d+B*_,i[13]=D*r+T*l+k*u+B*f,i[14]=D*o+T*h+k*p+B*g,i[15]=D*a+T*c+k*m+B*v,i},mulMat3(e,t,i){i||(i=new FloatArrayType(9));const s=e[0],r=e[3],o=e[6],a=e[1],n=e[4],l=e[7],h=e[2],c=e[5],d=e[8],u=t[0],p=t[3],m=t[6],_=t[1],f=t[4],g=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*u+r*_+o*v,i[3]=s*p+r*f+o*b,i[6]=s*m+r*g+o*y,i[1]=a*u+n*_+l*v,i[4]=a*p+n*f+l*b,i[7]=a*m+n*g+l*y,i[2]=h*u+c*_+d*v,i[5]=h*p+c*f+d*b,i[8]=h*m+c*g+d*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=math.vec4()){const s=t[0],r=t[1],o=t[2],a=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*a,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*a,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*a,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*a,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],a=e[12],n=e[9];if(!t||e===t){const t=e[1],l=e[2],h=e[3],c=e[6],d=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=a,e[4]=t,e[6]=n,e[7]=o,e[8]=l,e[9]=c,e[11]=s,e[12]=h,e[13]=d,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=a,t[4]=e[1],t[5]=e[5],t[6]=n,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],a=e[5],n=e[6],l=e[7],h=e[8],c=e[9],d=e[10],u=e[11],p=e[12],m=e[13],_=e[14],f=e[15];return p*c*n*r-h*m*n*r-p*a*d*r+o*m*d*r+h*a*_*r-o*c*_*r-p*c*s*l+h*m*s*l+p*i*d*l-t*m*d*l-h*i*_*l+t*c*_*l+p*a*s*u-o*m*s*u-p*i*n*u+t*m*n*u+o*i*_*u-t*a*_*u-h*a*s*f+o*c*s*f+h*i*n*f-t*c*n*f-o*i*d*f+t*a*d*f},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],a=e[4],n=e[5],l=e[6],h=e[7],c=e[8],d=e[9],u=e[10],p=e[11],m=e[12],_=e[13],f=e[14],g=e[15],v=i*n-s*a,b=i*l-r*a,y=i*h-o*a,M=s*l-r*n,w=s*h-o*n,P=r*h-o*l,x=c*_-d*m,E=c*f-u*m,A=c*g-p*m,C=d*f-u*_,R=d*g-p*_,S=u*g-p*f,L=1/(v*S-b*R+y*C+M*A-w*E+P*x);return t[0]=(n*S-l*R+h*C)*L,t[1]=(-s*S+r*R-o*C)*L,t[2]=(_*P-f*w+g*M)*L,t[3]=(-d*P+u*w-p*M)*L,t[4]=(-a*S+l*A-h*E)*L,t[5]=(i*S-r*A+o*E)*L,t[6]=(-m*P+f*y-g*b)*L,t[7]=(c*P-u*y+p*b)*L,t[8]=(a*R-n*A+h*x)*L,t[9]=(-i*R+s*A-o*x)*L,t[10]=(m*w-_*y+g*v)*L,t[11]=(-c*w+d*y-p*v)*L,t[12]=(-a*C+n*E-l*x)*L,t[13]=(i*C-s*E+r*x)*L,t[14]=(-m*M+_*b-f*v)*L,t[15]=(c*M-d*b+u*v)*L,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||math.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||math.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new FloatArrayType(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,math.translationMat4v(e,r))})(),translationMat4s:(e,t)=>math.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>math.translateMat4c(e[0],e[1],e[2],t),OLDtranslateMat4c(e,t,i,s){const r=s[12];s[0]+=r*e,s[4]+=r*t,s[8]+=r*i;const o=s[13];s[1]+=o*e,s[5]+=o*t,s[9]+=o*i;const a=s[14];s[2]+=a*e,s[6]+=a*t,s[10]+=a*i;const n=s[15];return s[3]+=n*e,s[7]+=n*t,s[11]+=n*i,s},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 a=s[11];s[8]+=a*e,s[9]+=a*t,s[10]+=a*i;const n=s[15];return s[12]+=n*e,s[13]+=n*t,s[14]+=n*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=math.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),a=1-o,n=s[0],l=s[1],h=s[2];let c,d,u,p,m,_;return c=n*l,d=l*h,u=h*n,p=n*r,m=l*r,_=h*r,(i=i||math.mat4())[0]=a*n*n+o,i[1]=a*c+_,i[2]=a*u-m,i[3]=0,i[4]=a*c-_,i[5]=a*l*l+o,i[6]=a*d+p,i[7]=0,i[8]=a*u+m,i[9]=a*d-p,i[10]=a*h*h+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>math.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=math.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=math.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new FloatArrayType(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,math.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=>math.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=math.mat4()){const s=e[0],r=e[1],o=e[2],a=e[3],n=s+s,l=r+r,h=o+o,c=s*n,d=s*l,u=s*h,p=r*l,m=r*h,_=o*h,f=a*n,g=a*l,v=a*h;return i[0]=1-(p+_),i[1]=d+v,i[2]=u-g,i[3]=0,i[4]=d-v,i[5]=1-(c+_),i[6]=m+f,i[7]=0,i[8]=u+g,i[9]=m-f,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=math.vec4()){const s=math.clamp,r=e[0],o=e[4],a=e[8],n=e[1],l=e[5],h=e[9],c=e[2],d=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-h,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(d,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[1]=Math.atan2(a,u),i[2]=Math.atan2(n,l)):(i[1]=Math.atan2(-c,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(d,-1,1)),Math.abs(d)<.99999?(i[1]=Math.atan2(-c,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(n,r))):"ZYX"===t?(i[1]=Math.asin(-s(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(d,u),i[2]=Math.atan2(n,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-h,l),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(a,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(d,l),i[1]=Math.atan2(a,r)):(i[0]=Math.atan2(-h,u),i[1]=0)),i},composeMat4:(e,t,i,s=math.mat4())=>(math.quaternionToRotationMat4(t,s),math.scaleMat4v(i,s),math.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new FloatArrayType(3),t=new FloatArrayType(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let a=math.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const n=math.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=math.lenVec3(e);math.determinantMat4(i)<0&&(a=-a),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const h=1/a,c=1/n,d=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=d,t[9]*=d,t[10]*=d,math.mat4ToQuaternion(t,r),o[0]=a,o[1]=n,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=math.mat4());const r=e[0],o=e[1],a=e[2],n=i[0],l=i[1],h=i[2],c=t[0],d=t[1],u=t[2];if(r===c&&o===d&&a===u)return math.identityMat4();let p,m,_,f,g,v,b,y,M,w;return p=r-c,m=o-d,_=a-u,f=l*(_*=w=1/Math.sqrt(p*p+m*m+_*_))-h*(m*=w),g=h*(p*=w)-n*_,v=n*m-l*p,(w=Math.sqrt(f*f+g*g+v*v))?(f*=w=1/w,g*=w,v*=w):(f=0,g=0,v=0),b=m*v-_*g,y=_*f-p*v,M=p*g-m*f,(w=Math.sqrt(b*b+y*y+M*M))?(b*=w=1/w,y*=w,M*=w):(b=0,y=0,M=0),s[0]=f,s[1]=b,s[2]=p,s[3]=0,s[4]=g,s[5]=y,s[6]=m,s[7]=0,s[8]=v,s[9]=M,s[10]=_,s[11]=0,s[12]=-(f*r+g*o+v*a),s[13]=-(b*r+y*o+M*a),s[14]=-(p*r+m*o+_*a),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,a,n,l)=>math.lookAtMat4v([e,t,i],[s,r,o],[a,n,l],[]),orthoMat4c(e,t,i,s,r,o,a){a||(a=math.mat4());const n=t-e,l=s-i,h=o-r;return a[0]=2/n,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2/l,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/h,a[11]=0,a[12]=-(e+t)/n,a[13]=-(s+i)/l,a[14]=-(o+r)/h,a[15]=1,a},frustumMat4v(e,t,i){i||(i=math.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];math.addVec4(r,s,tempMat1),math.subVec4(r,s,tempMat2);const o=2*s[2],a=tempMat2[0],n=tempMat2[1],l=tempMat2[2];return i[0]=o/a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/n,i[6]=0,i[7]=0,i[8]=tempMat1[0]/a,i[9]=tempMat1[1]/n,i[10]=-tempMat1[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,a){a||(a=math.mat4());const n=t-e,l=s-i,h=o-r;return a[0]=2*r/n,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2*r/l,a[6]=0,a[7]=0,a[8]=(t+e)/n,a[9]=(s+i)/l,a[10]=-(o+r)/h,a[11]=-1,a[12]=0,a[13]=0,a[14]=-o*r*2/h,a[15]=0,a},perspectiveMat4(e,t,i,s,r){const o=[],a=[];return o[2]=i,a[2]=s,a[1]=o[2]*Math.tan(e/2),o[1]=-a[1],a[0]=a[1]*t,o[0]=-a[0],math.frustumMat4v(o,a,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=math.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=math.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,a,n,l;const h=e[0],c=e[1],d=e[2],u=e[3],p=e[4],m=e[5],_=e[6],f=e[7],g=e[8],v=e[9],b=e[10],y=e[11],M=e[12],w=e[13],P=e[14],x=e[15];let E;for(let e=0;e{const e=new FloatArrayType(16),t=new FloatArrayType(16),i=new FloatArrayType(16);return function(s,r,o,a){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,a)}})(),lerpVec3(e,t,i,s,r,o){const a=o||math.vec3(),n=(e-t)/(i-t);return a[0]=s[0]+n*(r[0]-s[0]),a[1]=s[1]+n*(r[1]-s[1]),a[2]=s[2]+n*(r[2]-s[2]),a},lerpMat4(e,t,i,s,r,o){const a=o||math.mat4(),n=(e-t)/(i-t);return a[0]=s[0]+n*(r[0]-s[0]),a[1]=s[1]+n*(r[1]-s[1]),a[2]=s[2]+n*(r[2]-s[2]),a[3]=s[3]+n*(r[3]-s[3]),a[4]=s[4]+n*(r[4]-s[4]),a[5]=s[5]+n*(r[5]-s[5]),a[6]=s[6]+n*(r[6]-s[6]),a[7]=s[7]+n*(r[7]-s[7]),a[8]=s[8]+n*(r[8]-s[8]),a[9]=s[9]+n*(r[9]-s[9]),a[10]=s[10]+n*(r[10]-s[10]),a[11]=s[11]+n*(r[11]-s[11]),a[12]=s[12]+n*(r[12]-s[12]),a[13]=s[13]+n*(r[13]-s[13]),a[14]=s[14]+n*(r[14]-s[14]),a[15]=s[15]+n*(r[15]-s[15]),a},flatten(e){const t=[];let i,s,r,o,a;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=math.vec4()){const s=e[0]*math.DEGTORAD/2,r=e[1]*math.DEGTORAD/2,o=e[2]*math.DEGTORAD/2,a=Math.cos(s),n=Math.cos(r),l=Math.cos(o),h=Math.sin(s),c=Math.sin(r),d=Math.sin(o);return"XYZ"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l-h*c*d):"YXZ"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l+h*c*d):"ZXY"===t?(i[0]=h*n*l-a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l-h*c*d):"ZYX"===t?(i[0]=h*n*l-a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l+h*c*d):"YZX"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l-h*c*d):"XZY"===t&&(i[0]=h*n*l-a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l+h*c*d),i},mat4ToQuaternion(e,t=math.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],a=e[5],n=e[9],l=e[2],h=e[6],c=e[10];let d;const u=i+a+c;return u>0?(d=.5/Math.sqrt(u+1),t[3]=.25/d,t[0]=(h-n)*d,t[1]=(r-l)*d,t[2]=(o-s)*d):i>a&&i>c?(d=2*Math.sqrt(1+i-a-c),t[3]=(h-n)/d,t[0]=.25*d,t[1]=(s+o)/d,t[2]=(r+l)/d):a>c?(d=2*Math.sqrt(1+a-i-c),t[3]=(r-l)/d,t[0]=(s+o)/d,t[1]=.25*d,t[2]=(n+h)/d):(d=2*Math.sqrt(1+c-i-a),t[3]=(o-s)/d,t[0]=(r+l)/d,t[1]=(n+h)/d,t[2]=.25*d),t},vec3PairToQuaternion(e,t,i=math.vec4()){const s=Math.sqrt(math.dotVec3(e,e)*math.dotVec3(t,t));let r=s+math.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])):math.cross3Vec3(e,t,i),i[3]=r,math.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=math.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 FloatArrayType(16);return(t,i,s)=>(s=s||math.vec3(),math.quaternionToRotationMat4(t,e),math.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=math.vec4()){const s=e[0],r=e[1],o=e[2],a=e[3],n=t[0],l=t[1],h=t[2],c=t[3];return i[0]=a*n+s*c+r*h-o*l,i[1]=a*l+r*c+o*n-s*h,i[2]=a*h+o*c+s*l-r*n,i[3]=a*c-s*n-r*l-o*h,i},vec3ApplyQuaternion(e,t,i=math.vec3()){const s=t[0],r=t[1],o=t[2],a=e[0],n=e[1],l=e[2],h=e[3],c=h*s+n*o-l*r,d=h*r+l*s-a*o,u=h*o+a*r-n*s,p=-a*s-n*r-l*o;return i[0]=c*h+p*-a+d*-l-u*-n,i[1]=d*h+p*-n+u*-a-c*-l,i[2]=u*h+p*-l+c*-n-d*-a,i},quaternionToMat4(e,t){t=math.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],a=2*i,n=2*s,l=2*r,h=a*o,c=n*o,d=l*o,u=a*i,p=n*i,m=l*i,_=n*s,f=l*s,g=l*r;return t[0]=1-(_+g),t[1]=p+d,t[2]=m-c,t[4]=p-d,t[5]=1-(u+g),t[6]=f+h,t[8]=m+c,t[9]=f-h,t[10]=1-(u+_),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],a=i+i,n=s+s,l=r+r,h=i*a,c=i*n,d=i*l,u=s*n,p=s*l,m=r*l,_=o*a,f=o*n,g=o*l;return t[0]=1-(u+m),t[4]=c-g,t[8]=d+f,t[1]=c+g,t[5]=1-(h+m),t[9]=p-_,t[2]=d-f,t[6]=p+_,t[10]=1-(h+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=math.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)=>math.normalizeQuaternion(math.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=math.vec4()){const i=(e=math.normalizeQuaternion(e,tempVec4))[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 FloatArrayType(e||6),AABB2:e=>new FloatArrayType(e||4),OBB3:e=>new FloatArrayType(e||32),OBB2:e=>new FloatArrayType(e||16),Sphere3:(e,t,i,s)=>new FloatArrayType([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,a,n;const l=e[0],h=e[1],c=e[2],d=e[3],u=e[4],p=e[5],m=e[6],_=e[7],f=e[8],g=e[9],v=e[10],b=e[11],y=e[12],M=e[13],w=e[14],P=e[15];for(s=0;s{const e=new FloatArrayType(3),t=new FloatArrayType(3),i=new FloatArrayType(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],math.subVec3(t,e,i),Math.abs(math.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new FloatArrayType(3),t=new FloatArrayType(3),i=new FloatArrayType(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=math.subVec3(t,e,i),a=r[0]-s[0],n=s[3]-r[0],l=r[1]-s[1],h=s[4]-r[1],c=r[2]-s[2],d=s[5]-r[2];return o[0]+=a>n?a:n,o[1]+=l>h?l:h,o[2]+=c>d?c:d,Math.abs(math.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||math.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||math.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=math.AABB3())=>(e[0]=math.MAX_DOUBLE,e[1]=math.MAX_DOUBLE,e[2]=math.MAX_DOUBLE,e[3]=math.MIN_DOUBLE,e[4]=math.MIN_DOUBLE,e[5]=math.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=math.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 Float32Array(3);return(t,i,s)=>{i=i||math.AABB3();let r,o,a,n=math.MAX_DOUBLE,l=math.MAX_DOUBLE,h=math.MAX_DOUBLE,c=math.MIN_DOUBLE,d=math.MIN_DOUBLE,u=math.MIN_DOUBLE;for(let i=0,p=t.length;ic&&(c=r),o>d&&(d=o),a>u&&(u=a);return i[0]=n,i[1]=l,i[2]=h,i[3]=c,i[4]=d,i[5]=u,i}})(),OBB3ToAABB3(e,t=math.AABB3()){let i,s,r,o=math.MAX_DOUBLE,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=math.MIN_DOUBLE,h=math.MIN_DOUBLE,c=math.MIN_DOUBLE;for(let t=0,d=e.length;tl&&(l=i),s>h&&(h=s),r>c&&(c=r);return t[0]=o,t[1]=a,t[2]=n,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=math.AABB3()){let i,s,r,o=math.MAX_DOUBLE,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=math.MIN_DOUBLE,h=math.MIN_DOUBLE,c=math.MIN_DOUBLE;for(let t=0,d=e.length;tl&&(l=i),s>h&&(h=s),r>c&&(c=r);return t[0]=o,t[1]=a,t[2]=n,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new Float32Array(3);return(t,i)=>{i=i||math.vec4();let s,r=0,o=0,a=0;const n=t.length;for(s=0;sh&&(h=l);return i[3]=h,i}})(),positions3ToSphere3:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s)=>{s=s||math.vec4();let r,o=0,a=0,n=0;const l=i.length;let h=0;for(r=0;rh&&(h=d);return s[3]=h,s}})(),OBB3ToSphere3:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s)=>{s=s||math.vec4();let r,o=0,a=0,n=0;const l=i.length,h=l/4;for(r=0;rd&&(d=c);return s[3]=d,s}})(),getSphere3Center:(e,t=math.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],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](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]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=math.MAX_DOUBLE,e[1]=math.MAX_DOUBLE,e[2]=math.MIN_DOUBLE,e[3]=math.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]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]),s<=-t&&r<=-t?-1:s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=math.AABB2()){let i,s,r,o,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=math.MIN_DOUBLE,h=math.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>h&&(h=s);return t[0]=a,t[1]=n,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]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),a=.5*(s-t),n=r*r;return(2*t-2*i+o+a)*(r*n)+(-3*t+3*i-2*o-a)*n+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=math.vec3()){const r=t[0]-e[0],o=t[1]-e[1],a=t[2]-e[2],n=i[0]-e[0],l=i[1]-e[1],h=i[2]-e[2],c=o*h-a*l,d=a*n-r*h,u=r*l-o*n,p=Math.sqrt(c*c+d*d+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/p,s[1]=d/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3);return(o,a,n,l,h,c)=>{c=c||math.vec3();const d=math.subVec3(l,n,e),u=math.subVec3(h,n,t),p=math.cross3Vec3(a,u,i),m=math.dotVec3(d,p);if(m<1e-6)return null;const _=math.subVec3(o,n,s),f=math.dotVec3(_,p);if(f<0||f>m)return null;const g=math.cross3Vec3(_,d,r),v=math.dotVec3(a,g);if(v<0||f+v>m)return null;const b=math.dotVec3(u,g)/m;return c[0]=o[0]+b*a[0],c[1]=o[1]+b*a[1],c[2]=o[2]+b*a[2],c}})(),rayPlaneIntersect:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3);return(r,o,a,n,l,h)=>{h=h||math.vec3(),o=math.normalizeVec3(o,e);const c=math.subVec3(n,a,t),d=math.subVec3(l,a,i),u=math.cross3Vec3(c,d,s);math.normalizeVec3(u,u);const p=-math.dotVec3(a,u),m=-(math.dotVec3(r,u)+p)/math.dotVec3(o,u);return h[0]=r[0]+m*o[0],h[1]=r[1]+m*o[1],h[2]=r[2]+m*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3);return(s,r,o,a,n)=>{const l=math.subVec3(a,r,e),h=math.subVec3(o,r,t),c=math.subVec3(s,r,i),d=math.dotVec3(l,l),u=math.dotVec3(l,h),p=math.dotVec3(l,c),m=math.dotVec3(h,h),_=math.dotVec3(h,c),f=d*m-u*u;if(0===f)return null;const g=1/f,v=(m*p-u*_)*g,b=(d*_-u*p)*g;return n[0]=1-v-b,n[1]=b,n[2]=v,n}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=math.vec3()){const o=e[0],a=e[1],n=e[2];return r[0]=t[0]*o+i[0]*a+s[0]*n,r[1]=t[1]*o+i[1]*a+s[1]*n,r[2]=t[2]*o+i[2]*a+s[2]*n,r},mergeVertices(e,t,i,s){const r={},o=[],a=[],n=t?[]:null,l=i?[]:null,h=[];let c,d,u,p;let m,_,f=0;for(m=0,_=e.length;m<_;m+=3)c=e[m],d=e[m+1],u=e[m+2],void 0===r[p=`${Math.round(1e4*c)}_${Math.round(1e4*d)}_${Math.round(1e4*u)}`]&&(r[p]=a.length/3,a.push(c),a.push(d),a.push(u),t&&(n.push(t[m]),n.push(t[m+1]),n.push(t[m+2])),i&&(l.push(i[f]),l.push(i[f+1]))),o[m/3]=r[p],f+=2;for(m=0,_=s.length;m<_;m++)h[m]=o[s[m]];const g={positions:a,indices:h};return n&&(g.normals=n),l&&(g.uv=l),g},buildNormals:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3),o=new Float32Array(3);return(a,n,l)=>{let h,c;const d=new Array(a.length/3);let u,p,m,_,f,g,v;for(h=0,c=n.length;h{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3),o=new Float32Array(3),a=new Float32Array(3);return(n,l,h)=>{const c=new Float32Array(n.length);for(let d=0;d>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=3*(n=t[i]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,a=3*(n=t[i+1]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,a=3*(n=t[i+2]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],a={};let n,l,h,c,d;let u,p,m,_,f,g;for(p=0,_=e.length;p<_;p+=3){u=p/3,l=e[p],h=e[p+1],c=e[p+2],void 0===r[d=`${Math.round(1e4*l)}_${Math.round(1e4*h)}_${Math.round(1e4*c)}`]?r[d]=[u]:r[d].push(u);const i=math.normalizeVec3([t[p],t[p+1],t[p+2]]);o[u]=i,n=math.vec4([i[0],i[1],i[2],1]),a[u]=n}for(d in r)if(r.hasOwnProperty(d)){const e=r[d],t=e.length;for(p=0;p{const e=new Float32Array(16),t=new Float32Array(16),i=new Float32Array(4),s=new Float32Array(4),r=new Float32Array(4),o=new Float32Array(4);return(a,n,l,h,c,d)=>{const u=math.mulMat4(l,n,e),p=math.inverseMat4(u,t),m=a.width,_=a.height,f=(h[0]-m/2)/(m/2),g=-(h[1]-_/2)/(_/2);i[0]=f,i[1]=g,i[2]=-1,i[3]=1,math.transformVec4(p,i,s),math.mulVec4Scalar(s,1/s[3]),r[0]=f,r[1]=g,r[2]=1,r[3]=1,math.transformVec4(p,r,o),math.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],math.subVec3(o,s,d),math.normalizeVec3(d)}})(),canvasPosToLocalRay:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s,r,o,a,n,l)=>{math.canvasPosToWorldRay(i,s,r,a,e,t),math.worldRayToLocalRay(o,e,t,n,l)}})(),worldRayToLocalRay:(()=>{const e=new Float32Array(16),t=new Float32Array(4),i=new Float32Array(4);return(s,r,o,a,n)=>{const l=math.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,math.transformVec4(l,t,i),a[0]=i[0],a[1]=i[1],a[2]=i[2],math.transformVec3(l,o,n)}})(),buildKDTree:(()=>{const e=10,t=20,i=new Float32Array;return(s,r)=>{const o=s.length/3,a=new Array(o);for(let e=0;el[3]&&(l[3]=a[t]),a[t+1]l[4]&&(l[4]=a[t+1]),a[t+2]l[5]&&(l[5]=a[t+2])}}if(r.lengthe)return h.triangles=r,h.leaf=!0,h;i[0]=l[3]-l[0],i[1]=l[4]-l[1],i[2]=l[5]-l[2];let p=0;i[1]>i[p]&&(p=1),i[2]>i[p]&&(p=2),h.splitDim=p;const m=(l[p]+l[p+3])/2,_=new Array(r.length);let f=0;const g=new Array(r.length);let v=0;for(c=0,d=r.length;c=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=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const n=Math.sqrt(r*r+o*o+a*a);t[s+0]=r/n,t[s+1]=o/n,t[s+2]=a/n,s+=3}return t}};math.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const a=new Uint16Array(3),n=new Uint16Array(3),l=new Uint16Array(3),h=math.vec3(),c=math.vec3(),d=math.vec3(),u=math.vec3(),p=math.vec3(),m=math.vec3(),_=math.vec3();return function(f,g,v,b){!function(r,o){const a={};let n,l,h,c;const d=Math.pow(10,4);let u,p,m=0;for(u=0,p=r.length;uM)||(T=i[R.index1],k=i[R.index2],(!B&&T>65535||k>65535)&&(B=!0),y.push(T),y.push(k));return B?new Uint32Array(y):new Uint16Array(y)}}();const color=math.vec3();class ModelMemento{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){const s=t.rootMetaObject;if(!s)return;const r=s.getObjectIDsInSubtree();this.numObjects=0,this._mask=i?utils.apply(i,{}):null;const o=e.objects,a=!i||i.visible,n=!i||i.edges,l=!i||i.xrayed,h=!i||i.highlighted,c=!i||i.selected,d=!i||i.clippable,u=!i||i.pickable,p=!i||i.colorize,m=!i||i.opacity;for(var _=0,f=r.length;_{this._saveModelMemento(e)}),this.bimViewer._modelsExplorer.on("modelUnloaded",e=>{this._destroyModelMemento(e)}),this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{this.getEnabled()&&this.reset(),e.preventDefault()})}_saveModelMemento(e){const t=this.viewer.metaScene.metaModels[e];if(!t)return;const i=new ModelMemento;i.saveObjects(this.viewer.scene,t,{visible:!0,edges:!0,xrayed:!0,highlighted:!0,selected:!0,clippable:!0,pickable:!0,colorize:!0,opacity:!1}),this._modelMementos[e]=i}_restoreModelMemento(e){const t=this.viewer.metaScene.metaModels[e];t&&this._modelMementos[e].restoreObjects(this.viewer.scene,t)}_destroyModelMemento(e){delete this._modelMementos[e]}reset(){const e=this.viewer.scene.modelIds;for(var t=0,i=e.length;t{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{this.getEnabled()&&this.fit(),e.preventDefault()})}fit(){const e=this.viewer.scene,t=e.getAABB(e.visibleObjectIds);this.viewer.cameraFlight.flyTo({aabb:t}),this.viewer.cameraControl.pivotPos=math.getAABB3Center(t,tempVec3)}set fov(e){this.viewer.scene.cameraFlight.fitFOV=e}get fov(){return this.viewer.scene.cameraFlight.fitFOV}set duration(e){this.viewer.scene.cameraFlight.duration=e}get duration(){return this.viewer.scene.cameraFlight.duration}}class FirstPersonMode extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement,s=this.viewer.cameraControl,r=t.cameraControlNavModeMediator;s.navMode="orbit",s.followPointer=!0,this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),this.on("active",e=>{r.setFirstPersonModeActive(e),e?(s.followPointer=!0,s.pivoting=!1):s.pivoting=!0}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)})}}function closeEnough(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class HideTool extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?(i.classList.add("active"),this.viewer.cameraControl.doublePickFlyTo=!1):(i.classList.remove("active"),this.viewer.cameraControl.doublePickFlyTo=!0)}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._init()}_init(){var e=null;this._onHover=this.viewer.cameraControl.on("hover",t=>{this.getActive()&&this.getEnabled()&&(e&&(e.highlighted=!1,e=null),t.entity&&t.entity.isObject&&((e=t.entity).highlighted=!0))}),this._onHoverOff=this.viewer.cameraControl.on("hoverOff",t=>{this.getActive()&&this.getEnabled()&&e&&(e.highlighted=!1,e=null)});const t=math.vec2(),i=this.viewer.scene.input;this._onMousedown=i.on("mousedown",e=>{!i.mouseDownLeft||i.mouseDownRight||i.mouseDownMiddle||(t[0]=e[0],t[1]=e[1])}),this._onMouseup=i.on("mouseup",i=>{if(this.getActive()&&this.getEnabled()&&e){if(!closeEnough(t,i))return void(e=null);e.visible=!1,e.highlighted=!1,e=null}})}}function closeEnough$1(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class SelectionTool extends Controller{constructor(e,t){if(super(e),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{if(e)i.classList.add("active");else{i.classList.remove("active");const e=this.viewer.scene;e.setObjectsHighlighted(e.highlightedObjectIds,!1)}}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._initSectionMode()}_initSectionMode(){const e=this.viewer,t=e.cameraControl;var i=null;this._onHover=t.on("hover",e=>{this.getActive()&&this.getEnabled()&&(i&&(i.highlighted=!1,i=null),e.entity&&e.entity.isObject&&((i=e.entity).highlighted=!0))}),this._onHoverOff=t.on("hoverOff",e=>{this.getActive()&&this.getEnabled()&&i&&(i.highlighted=!1,i=null)});const s=math.vec2(),r=e.scene.input;this._onMousedown=r.on("mousedown",e=>{this.getActive()&&this.getEnabled()&&(!r.mouseDownLeft||r.mouseDownRight||r.mouseDownMiddle||(s[0]=e[0],s[1]=e[1]))}),this._onMouseup=r.on("mouseup",e=>{if(this.getActive()&&this.getEnabled()&&i){if(!closeEnough$1(s,e))return void(i=null);i.selected=!i.selected,i=null}})}}function closeEnough$2(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class QueryTool extends Controller{constructor(e,t){if(super(e),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._init()}_init(){const e=this.viewer,t=e.cameraControl;var i=null;this._onHover=t.on("hover",e=>{this.getActive()&&this.getEnabled()&&(i&&(i.highlighted=!1,i=null),e.entity&&e.entity.isObject&&((i=e.entity).highlighted=!0))}),this._onHoverOff=t.on("hoverOff",e=>{this.getActive()&&this.getEnabled()&&i&&(i.highlighted=!1,i=null)});const s=math.vec2(),r=e.scene.input;this._onMousedown=r.on("mousedown",e=>{this.getActive()&&this.getEnabled()&&(!r.mouseDownLeft||r.mouseDownRight||r.mouseDownMiddle||(s[0]=e[0],s[1]=e[1]))}),this._onMouseup=r.on("mouseup",t=>{if(this.getActive()&&this.getEnabled())if(i){if(!closeEnough$2(s,t))return void(i=null);const r=i.model;if(!r)return;const o=this.bimViewer.getLoadedProjectId();if(!o)return void this.error("Query tool: should be a project loaded - ignoring query-pick");const a=r.id,n=i.id,l=e.metaScene.metaObjects[n];if(!l)return;const h={projectId:o,modelId:a,objectId:n,objectName:l.name,objectType:l.type};this.fire("queryPicked",h),i=null}else this.fire("queryNotPicked",!1)})}}class Plugin{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._eventSubs={},t.addPlugin(this)}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=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 stats={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}},scenesRenderInfo={},sceneIDMap=new Map,taskQueue=new Queue,tickEvent={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},taskBudget=10,fpsSamples=[],numFPSSamples=30;let elapsedTime,lastTime=0,totalFPS=0;function Core(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(core.scenes[e.id])return void console.error(`[ERROR] Scene ${utils.inQuotes(e.id)} already exists`)}else e.id=sceneIDMap.addItem({});core.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;scenesRenderInfo[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},stats.components.scenes++,e.once("destroyed",()=>{sceneIDMap.removeItem(e.id),delete core.scenes[e.id],delete scenesRenderInfo[e.id],stats.components.scenes--})},this.clear=function(){let e;for(const t in core.scenes)core.scenes.hasOwnProperty(t)&&(e=core.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete core.scenes[e.id]))},this.scheduleTask=function(e,t){taskQueue.push(e),taskQueue.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;taskQueue.length>0&&(e<0||s0){var t=1e3/(elapsedTime=e-lastTime);totalFPS+=t,fpsSamples.push(t),fpsSamples.length>=30&&(totalFPS-=fpsSamples.shift()),stats.frame.fps=Math.round(totalFPS/fpsSamples.length)}runTasks(e),fireTickEvents(e),renderScenes(),lastTime=e,window.requestAnimationFrame(frame)};function runTasks(e){const t=core.runTasks(e+taskBudget),i=core.getNumTasks();stats.frame.tasksRun=t,stats.frame.tasksScheduled=i,stats.frame.tasksBudget=taskBudget}function fireTickEvents(e){for(var t in tickEvent.time=e,core.scenes)if(core.scenes.hasOwnProperty(t)){var i=core.scenes[t];tickEvent.sceneId=t,tickEvent.startTime=i.startTime,tickEvent.deltaTime=null!=tickEvent.prevTime?tickEvent.time-tickEvent.prevTime:0,i.fire("tick",tickEvent,!0)}tickEvent.prevTime=e}function renderScenes(){const e=core.scenes;let t,i,s,r,o;for(o in e)e.hasOwnProperty(o)&&(t=e[o],(i=scenesRenderInfo[o])||(i=scenesRenderInfo[o]={}),s=t.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==s&&(i.ticksPerOcclusionTest=s,i.renderCountdown=s),--t.occlusionTestCountdown<=0&&(t.doOcclusionTest(),t.occlusionTestCountdown=s),r=t.ticksPerRender,i.ticksPerRender!==r&&(i.ticksPerRender=r,i.renderCountdown=r),0==--i.renderCountdown&&(t.render(!1),i.renderCountdown=r))}window.requestAnimationFrame(frame);class Component{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 Component))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e,this._renderer=this.scene._renderer}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.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty()}glResort(){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(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Map),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);const r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;const o=this._events[e];return void 0!==o&&t.call(i||this,o),r}off(e){if(void 0===e||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+" "+utils.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,a=e.on,n=!1!==e.recompiles;if(i&&(utils.isNumeric(i)||utils.isString(i))){const e=i;if(!(i=this.scene.components[e]))return void this.error("Component not found: "+utils.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]))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+" "+utils.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+utils.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,d;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(c=0,d=(h=e.subs).length;c{delete this._ownedComponents[e.id]},this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():core.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(i=(t=this._attachments[e]).component,r=0,o=(s=t.subs).length;r0){for(R=f.length/3,g.push(0),g.push(1),g.push(0),v.push(.5),v.push(.5),f.push(0+l),f.push(d+h),f.push(0+c),M=0;M<=r;M++)w=Math.sin(M*p),P=Math.cos(M*p),S=.5*Math.sin(M*p)+.5,L=.5*Math.cos(M*p)+.5,g.push(t*w),g.push(1),g.push(t*P),v.push(S),v.push(L),f.push(t*w+l),f.push(d+h),f.push(t*P+c);for(M=0;M0){for(R=f.length/3,g.push(0),g.push(-1),g.push(0),v.push(.5),v.push(.5),f.push(0+l),f.push(0-d+h),f.push(0+c),M=0;M<=r;M++)w=Math.sin(M*p),P=Math.cos(M*p),S=.5*Math.sin(M*p)+.5,L=.5*Math.cos(M*p)+.5,g.push(i*w),g.push(-1),g.push(i*P),v.push(S),v.push(L),f.push(i*w+l),f.push(0-d+h),f.push(i*P+c);for(M=0;M360&&(o=360);const a=e.center;let n=a?a[0]:0,l=a?a[1]:0;const h=a?a[2]:0,c=[],d=[],u=[],p=[];let m,_,f,g,v,b,y,M,w,P,x,E;for(M=0;M<=r;M++)for(y=0;y<=s;y++)m=y/s*o,_=.785398+M/r*Math.PI*2,n=t*Math.cos(m),l=t*Math.sin(m),f=(t+i*Math.cos(_))*Math.cos(m),g=(t+i*Math.cos(_))*Math.sin(m),v=i*Math.sin(_),c.push(f+n),c.push(g+l),c.push(v+h),u.push(1-y/s),u.push(M/r),b=math.normalizeVec3(math.subVec3([f,g,v],[n,l,h],[]),[]),d.push(b[0]),d.push(b[1]),d.push(b[2]);for(M=1;M<=r;M++)for(y=1;y<=s;y++)w=(s+1)*M+y-1,P=(s+1)*(M-1)+y-1,x=(s+1)*(M-1)+y,E=(s+1)*M+y,p.push(w),p.push(P),p.push(x),p.push(x),p.push(E),p.push(w);return utils.apply(e,{positions:c,normals:d,uv:u,indices:p})}class Geometry extends Component{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),stats.memory.meshes++}destroy(){super.destroy(),stats.memory.meshes--}}class ArrayBuf{constructor(e,t,i,s,r,o,a,n,l){switch(this._gl=e,this.type=t,this.allocated=!1,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=!!a,this.stride=n||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)))}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)}}const WEBGL_INFO={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},canvas=document.createElement("canvas");if(canvas){const e=canvas.getContext("webgl",{antialias:!0})||canvas.getContext("experimental-webgl",{antialias:!0});WEBGL_INFO.WEBGL=!!e,WEBGL_INFO.WEBGL&&(WEBGL_INFO.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?WEBGL_INFO.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?WEBGL_INFO.FS_MAX_FLOAT_PRECISION="mediump":WEBGL_INFO.FS_MAX_FLOAT_PRECISION="lowp":WEBGL_INFO.FS_MAX_FLOAT_PRECISION="mediump",WEBGL_INFO.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),WEBGL_INFO.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),WEBGL_INFO.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),WEBGL_INFO.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),WEBGL_INFO.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),WEBGL_INFO.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),WEBGL_INFO.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),WEBGL_INFO.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),WEBGL_INFO.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),WEBGL_INFO.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach(function(e){WEBGL_INFO.SUPPORTED_EXTENSIONS[e]=!0}),WEBGL_INFO.depthTexturesSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.WEBGL_depth_texture)}var buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const a=new Uint16Array(3),n=new Uint16Array(3),l=new Uint16Array(3),h=math.vec3(),c=math.vec3(),d=math.vec3(),u=math.vec3(),p=math.vec3(),m=math.vec3(),_=math.vec3();return function(f,g,v,b){!function(r,o){const a={};let n,l,h,c;const d=Math.pow(10,4);let u,p,m=0;for(u=0,p=r.length;uM)||(T=i[R.index1],k=i[R.index2],(!B&&T>65535||k>65535)&&(B=!0),y.push(T),y.push(k));return B?new Uint32Array(y):new Uint16Array(y)}}();function getPositionsBounds(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;sa&&(r=i,a=o),(o=dot(e,n,s=octDecodeVec2(i=octEncodeVec3(e,n,"floor","ceil"))))>a&&(r=i,a=o),(o=dot(e,n,s=octDecodeVec2(i=octEncodeVec3(e,n,"ceil","ceil"))))>a&&(r=i,a=o),t[n]=r[0],t[n+1]=r[1];return t}function octEncodeVec3(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 octDecodeVec2(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 dot(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}function decompressUV(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]}function decompressUVs(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s=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}function decompressNormals(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const n=Math.sqrt(r*r+o*o+a*a);t[s+0]=r/n,t[s+1]=o/n,t[s+2]=a/n,s+=3}return t}const geometryCompressionUtils={getPositionsBounds:getPositionsBounds,createPositionsDecodeMatrix:createPositionsDecodeMatrix,compressPositions:compressPositions,decompressPositions:decompressPositions,decompressPosition:decompressPosition,decompressAABB:decompressAABB,getUVBounds:getUVBounds,compressUVs:compressUVs,decompressUVs:decompressUVs,decompressUV:decompressUV,compressNormals:compressNormals,decompressNormals:decompressNormals,decompressNormal:decompressNormal},memoryStats=stats.memory,bigIndicesSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,IndexArrayType=bigIndicesSupported?Uint32Array:Uint16Array,tempAABB=math.AABB3();class ReadableGeometry extends Geometry{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new RenderState({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=geometryCompressionUtils.getPositionsBounds(t.positions),s=geometryCompressionUtils.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=geometryCompressionUtils.getUVBounds(t.uv),s=geometryCompressionUtils.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);if(t.normals&&(this._state.compressGeometry?i.normals=geometryCompressionUtils.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices){if(!bigIndicesSupported&&t.indices.constructor===Uint32Array)return void this.error("This WebGL implementation does not support Uint32Array");i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new IndexArrayType(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),memoryStats.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),memoryStats.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),memoryStats.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),memoryStats.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),memoryStats.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),memoryStats.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=buildEdgeIndices(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),memoryStats.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=math.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),memoryStats.positions+=this._pickTrianglePositionsBuf.numItems,memoryStats.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),geometryCompressionUtils.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=geometryCompressionUtils.getPositionsBounds(e),s=geometryCompressionUtils.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),geometryCompressionUtils.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),geometryCompressionUtils.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=math.AABB3()),math.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=math.OBB3()),math.positions3ToAABB3(this._state.positions,tempAABB,this._state.positionsDecodeMatrix),math.AABB3ToOBB3(tempAABB,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),memoryStats.meshes--}}class Material extends Component{get type(){return"Material"}constructor(e,t={}){super(e,t),stats.memory.materials++}destroy(){super.destroy(),stats.memory.materials--}}const alphaModes={opaque:0,mask:1,blend:2},alphaModeNames=["opaque","mask","blend"];class PhongMaterial extends Material{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new RenderState({type:"PhongMaterial",ambient:math.vec3([1,1,1]),diffuse:math.vec3([1,1,1]),specular:math.vec3([1,1,1]),emissive:math.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=void 0!==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=alphaModes[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 alphaModeNames[this._state.alphaMode]}set alphaCutoff(e){null!==e&&void 0!==e||(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const PRESETS={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:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],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 EmphasisMaterial extends Material{get type(){return"EmphasisMaterial"}get presets(){return PRESETS}constructor(e,t={}){super(e,t),this._state=new RenderState({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!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)):(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)}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=void 0!==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=void 0!==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 preset(e){if(e=e||"default",this._preset===e)return;const t=PRESETS[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._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(PRESETS).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const angleAxis=new Float32Array(4),q1=new Float32Array(4),q2=new Float32Array(4),xAxis=new Float32Array([1,0,0]),yAxis=new Float32Array([0,1,0]),zAxis=new Float32Array([0,0,1]),veca=new Float32Array(3),vecb=new Float32Array(3),identityMat=math.identityMat4();class Node extends Component{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=math.vec3(),this._quaternion=math.identityQuaternion(),this._rotation=math.vec3(),this._position=math.vec3(),this._offset=math.vec3(),this._localMatrix=math.identityMat4(),this._worldMatrix=math.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.rtcCenter=t.rtcCenter,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;i0?"highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp":"mediump"}function buildVertexLambert(e){const t=e.scene._sectionPlanesState,i=e.scene._lightsState,s=e._geometry._state,r=e._state.billboard,o=e._state.stationary,a=t.sectionPlanes.length>0,n=!!s.compressGeometry;let l,h,c;const d=[];if(d.push("// Lambertian drawing vertex shader"),d.push("attribute vec3 position;"),d.push("uniform mat4 modelMatrix;"),d.push("uniform mat4 viewMatrix;"),d.push("uniform mat4 projMatrix;"),d.push("uniform vec4 colorize;"),d.push("uniform vec3 offset;"),n&&d.push("uniform mat4 positionsDecodeMatrix;"),a&&d.push("varying vec4 vWorldPosition;"),d.push("uniform vec4 lightAmbient;"),d.push("uniform vec4 materialColor;"),d.push("uniform vec3 materialEmissive;"),s.normalsBuf){for(d.push("attribute vec3 normal;"),d.push("uniform mat4 modelNormalMatrix;"),d.push("uniform mat4 viewNormalMatrix;"),l=0,h=i.lights.length;l= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),d.push(" }"),d.push(" return normalize(v);"),d.push("}"))}if(d.push("varying vec4 vColor;"),"points"===s.primitiveName&&d.push("uniform float pointSize;"),"spherical"!==r&&"cylindrical"!==r||(d.push("void billboard(inout mat4 mat) {"),d.push(" mat[0][0] = 1.0;"),d.push(" mat[0][1] = 0.0;"),d.push(" mat[0][2] = 0.0;"),"spherical"===r&&(d.push(" mat[1][0] = 0.0;"),d.push(" mat[1][1] = 1.0;"),d.push(" mat[1][2] = 0.0;")),d.push(" mat[2][0] = 0.0;"),d.push(" mat[2][1] = 0.0;"),d.push(" mat[2][2] =1.0;"),d.push("}")),d.push("void main(void) {"),d.push("vec4 localPosition = vec4(position, 1.0); "),d.push("vec4 worldPosition;"),n&&d.push("localPosition = positionsDecodeMatrix * localPosition;"),s.normalsBuf&&(n?d.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):d.push("vec4 localNormal = vec4(normal, 0.0); "),d.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),d.push("mat4 viewNormalMatrix2 = viewNormalMatrix;")),d.push("mat4 viewMatrix2 = viewMatrix;"),d.push("mat4 modelMatrix2 = modelMatrix;"),o&&d.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===r||"cylindrical"===r?(d.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),d.push("billboard(modelMatrix2);"),d.push("billboard(viewMatrix2);"),d.push("billboard(modelViewMatrix);"),s.normalsBuf&&(d.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),d.push("billboard(modelNormalMatrix2);"),d.push("billboard(viewNormalMatrix2);"),d.push("billboard(modelViewNormalMatrix);")),d.push("worldPosition = modelMatrix2 * localPosition;"),d.push("worldPosition.xyz = worldPosition.xyz + offset;"),d.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(d.push("worldPosition = modelMatrix2 * localPosition;"),d.push("worldPosition.xyz = worldPosition.xyz + offset;"),d.push("vec4 viewPosition = viewMatrix2 * worldPosition; ")),s.normalsBuf&&d.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);"),d.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),d.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),d.push("float lambertian = 1.0;"),s.normalsBuf)for(l=0,h=i.lights.length;l0,n=t.gammaOutput,l=[];if(l.push("// Lambertian drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),a)for(l.push("varying vec4 vWorldPosition;"),l.push("uniform bool clippable;"),r=0,o=i.sectionPlanes.length;r 0.0) { discard; }"),l.push("}")}return"points"===s.primitiveName&&(l.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),l.push("float r = dot(cxy, cxy);"),l.push("if (r > 1.0) {"),l.push(" discard;"),l.push("}")),n?l.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):l.push("gl_FragColor = vColor;"),l.push("}"),l}function buildVertexDraw(e){const t=e.scene,i=e._material,s=e._state,r=t._sectionPlanesState,o=e._geometry._state,a=t._lightsState;let n,l,h;const c=s.billboard,d=s.stationary,u=hasTextures(e),p=hasNormals(e),m=r.sectionPlanes.length>0,_=getReceivesShadow(e),f=!!o.compressGeometry,g=[];if(p&&i._normalMap&&g.push("#extension GL_OES_standard_derivatives : enable"),g.push("// Drawing vertex shader"),g.push("attribute vec3 position;"),f&&g.push("uniform mat4 positionsDecodeMatrix;"),g.push("uniform mat4 modelMatrix;"),g.push("uniform mat4 viewMatrix;"),g.push("uniform mat4 projMatrix;"),g.push("varying vec3 vViewPosition;"),g.push("uniform vec3 offset;"),m&&g.push("varying vec4 vWorldPosition;"),a.lightMaps.length>0&&g.push("varying vec3 vWorldNormal;"),p){for(g.push("attribute vec3 normal;"),g.push("uniform mat4 modelNormalMatrix;"),g.push("uniform mat4 viewNormalMatrix;"),g.push("varying vec3 vViewNormal;"),n=0,l=a.lights.length;n= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),g.push(" }"),g.push(" return normalize(v);"),g.push("}"))}if(u&&(g.push("attribute vec2 uv;"),g.push("varying vec2 vUV;"),f&&g.push("uniform mat3 uvDecodeMatrix;")),o.colors&&(g.push("attribute vec4 color;"),g.push("varying vec4 vColor;")),"points"===o.primitiveName&&g.push("uniform float pointSize;"),"spherical"!==c&&"cylindrical"!==c||(g.push("void billboard(inout mat4 mat) {"),g.push(" mat[0][0] = 1.0;"),g.push(" mat[0][1] = 0.0;"),g.push(" mat[0][2] = 0.0;"),"spherical"===c&&(g.push(" mat[1][0] = 0.0;"),g.push(" mat[1][1] = 1.0;"),g.push(" mat[1][2] = 0.0;")),g.push(" mat[2][0] = 0.0;"),g.push(" mat[2][1] = 0.0;"),g.push(" mat[2][2] =1.0;"),g.push("}")),_)for(g.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);"),n=0,l=a.lights.length;n0&&g.push("vWorldNormal = worldNormal;"),g.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),g.push("vec3 tmpVec3;"),g.push("float lightDist;"),n=0,l=a.lights.length;n0,h=hasNormals(e),c=r.uvBuf,d="PhongMaterial"===n.type,u="MetallicMaterial"===n.type,p="SpecularMaterial"===n.type,m=getReceivesShadow(e),_=(t.gammaInput,t.gammaOutput);let f,g;const v=[];if(v.push("// Drawing fragment shader"),h&&s._normalMap&&v.push("#extension GL_OES_standard_derivatives : enable"),v.push("precision "+getFragmentFloatPrecision(i)+" float;"),m&&(v.push("float unpackDepth (vec4 color) {"),v.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));"),v.push(" return dot(color, bitShift);"),v.push("}")),v.push("uniform float gammaFactor;"),v.push("vec4 linearToLinear( in vec4 value ) {"),v.push(" return value;"),v.push("}"),v.push("vec4 sRGBToLinear( in vec4 value ) {"),v.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 );"),v.push("}"),v.push("vec4 gammaToLinear( in vec4 value) {"),v.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),v.push("}"),_&&(v.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),v.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),v.push("}")),l){v.push("varying vec4 vWorldPosition;"),v.push("uniform bool clippable;");for(var b=0;b0&&(v.push("uniform samplerCube lightMap;"),v.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&v.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("uniform mat4 viewMatrix;"),v.push("#define PI 3.14159265359"),v.push("#define RECIPROCAL_PI 0.31830988618"),v.push("#define RECIPROCAL_PI2 0.15915494"),v.push("#define EPSILON 1e-6"),v.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),v.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),v.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),v.push("}"),v.push("struct IncidentLight {"),v.push(" vec3 color;"),v.push(" vec3 direction;"),v.push("};"),v.push("struct ReflectedLight {"),v.push(" vec3 diffuse;"),v.push(" vec3 specular;"),v.push("};"),v.push("struct Geometry {"),v.push(" vec3 position;"),v.push(" vec3 viewNormal;"),v.push(" vec3 worldNormal;"),v.push(" vec3 viewEyeDir;"),v.push("};"),v.push("struct Material {"),v.push(" vec3 diffuseColor;"),v.push(" float specularRoughness;"),v.push(" vec3 specularColor;"),v.push(" float shine;"),v.push("};"),d&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(v.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(v.push(" vec3 irradiance = "+TEXTURE_DECODE_FUNCS[a.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),v.push(" irradiance *= PI;"),v.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),v.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(v.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),v.push(" vec3 radiance = textureCube(reflectionMap, reflectVec).rgb * 0.2;"),v.push(" reflectedLight.specular += radiance;")),v.push("}")),v.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),v.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),v.push(" vec3 irradiance = dotNL * directLight.color * PI;"),v.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),v.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),v.push("}")),(u||p)&&(v.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),v.push(" float r = ggxRoughness + 0.0001;"),v.push(" return (2.0 / (r * r) - 2.0);"),v.push("}"),v.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),v.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),v.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),v.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),v.push("}"),a.reflectionMaps.length>0&&(v.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),v.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),v.push(" vec3 envMapColor = "+TEXTURE_DECODE_FUNCS[a.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),v.push(" return envMapColor;"),v.push("}")),v.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),v.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),v.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),v.push("}"),v.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),v.push(" float a2 = ( alpha * alpha );"),v.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),v.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),v.push(" return 1.0 / ( gl * gv );"),v.push("}"),v.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),v.push(" float a2 = ( alpha * alpha );"),v.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),v.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),v.push(" return 0.5 / max( gv + gl, EPSILON );"),v.push("}"),v.push("float D_GGX(const in float alpha, const in float dotNH) {"),v.push(" float a2 = ( alpha * alpha );"),v.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),v.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),v.push("}"),v.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),v.push(" float alpha = ( roughness * roughness );"),v.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),v.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),v.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),v.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),v.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),v.push(" vec3 F = F_Schlick( specularColor, dotLH );"),v.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),v.push(" float D = D_GGX( alpha, dotNH );"),v.push(" return F * (G * D);"),v.push("}"),v.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),v.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),v.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),v.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),v.push(" vec4 r = roughness * c0 + c1;"),v.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),v.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),v.push(" return specularColor * AB.x + AB.y;"),v.push("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(v.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(v.push(" vec3 irradiance = sRGBToLinear(textureCube(lightMap, geometry.worldNormal)).rgb;"),v.push(" irradiance *= PI;"),v.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),v.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(v.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),v.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),v.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),v.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),v.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),v.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),v.push("}")),v.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),v.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),v.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),v.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),v.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),v.push("}"))),v.push("varying vec3 vViewPosition;"),r.colors&&v.push("varying vec4 vColor;"),c&&(h&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&v.push("varying vec2 vUV;"),h&&(a.lightMaps.length>0&&v.push("varying vec3 vWorldNormal;"),v.push("varying vec3 vViewNormal;")),n.ambient&&v.push("uniform vec3 materialAmbient;"),n.baseColor&&v.push("uniform vec3 materialBaseColor;"),void 0!==n.alpha&&null!==n.alpha&&v.push("uniform vec4 materialAlphaModeCutoff;"),n.emissive&&v.push("uniform vec3 materialEmissive;"),n.diffuse&&v.push("uniform vec3 materialDiffuse;"),void 0!==n.glossiness&&null!==n.glossiness&&v.push("uniform float materialGlossiness;"),void 0!==n.shininess&&null!==n.shininess&&v.push("uniform float materialShininess;"),n.specular&&v.push("uniform vec3 materialSpecular;"),void 0!==n.metallic&&null!==n.metallic&&v.push("uniform float materialMetallic;"),void 0!==n.roughness&&null!==n.roughness&&v.push("uniform float materialRoughness;"),void 0!==n.specularF0&&null!==n.specularF0&&v.push("uniform float materialSpecularF0;"),c&&s._ambientMap&&(v.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&v.push("uniform mat4 ambientMapMatrix;")),c&&s._baseColorMap&&(v.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&v.push("uniform mat4 baseColorMapMatrix;")),c&&s._diffuseMap&&(v.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&v.push("uniform mat4 diffuseMapMatrix;")),c&&s._emissiveMap&&(v.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&v.push("uniform mat4 emissiveMapMatrix;")),h&&c&&s._metallicMap&&(v.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&v.push("uniform mat4 metallicMapMatrix;")),h&&c&&s._roughnessMap&&(v.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&v.push("uniform mat4 roughnessMapMatrix;")),h&&c&&s._metallicRoughnessMap&&(v.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&v.push("uniform mat4 metallicRoughnessMapMatrix;")),h&&s._normalMap&&(v.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&v.push("uniform mat4 normalMapMatrix;"),v.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),v.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),v.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),v.push(" vec2 st0 = dFdx( uv.st );"),v.push(" vec2 st1 = dFdy( uv.st );"),v.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),v.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),v.push(" vec3 N = normalize( surf_norm );"),v.push(" vec3 mapN = texture2D( normalMap, uv ).xyz * 2.0 - 1.0;"),v.push(" mat3 tsn = mat3( S, T, N );"),v.push(" return normalize( tsn * mapN );"),v.push("}")),c&&s._occlusionMap&&(v.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&v.push("uniform mat4 occlusionMapMatrix;")),c&&s._alphaMap&&(v.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&v.push("uniform mat4 alphaMapMatrix;")),h&&c&&s._specularMap&&(v.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&v.push("uniform mat4 specularMapMatrix;")),h&&c&&s._glossinessMap&&(v.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&v.push("uniform mat4 glossinessMapMatrix;")),h&&c&&s._specularGlossinessMap&&(v.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&v.push("uniform mat4 materialSpecularGlossinessMapMatrix;")),h&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(v.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),v.push(" float fr = abs(dot(eyeDir, normal));"),v.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),v.push(" return pow(finalFr, power);"),v.push("}"),s._diffuseFresnel&&(v.push("uniform float diffuseFresnelCenterBias;"),v.push("uniform float diffuseFresnelEdgeBias;"),v.push("uniform float diffuseFresnelPower;"),v.push("uniform vec3 diffuseFresnelCenterColor;"),v.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(v.push("uniform float specularFresnelCenterBias;"),v.push("uniform float specularFresnelEdgeBias;"),v.push("uniform float specularFresnelPower;"),v.push("uniform vec3 specularFresnelCenterColor;"),v.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(v.push("uniform float alphaFresnelCenterBias;"),v.push("uniform float alphaFresnelEdgeBias;"),v.push("uniform float alphaFresnelPower;"),v.push("uniform vec3 alphaFresnelCenterColor;"),v.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(v.push("uniform float materialSpecularF0FresnelCenterBias;"),v.push("uniform float materialSpecularF0FresnelEdgeBias;"),v.push("uniform float materialSpecularF0FresnelPower;"),v.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),v.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(v.push("uniform float emissiveFresnelCenterBias;"),v.push("uniform float emissiveFresnelEdgeBias;"),v.push("uniform float emissiveFresnelPower;"),v.push("uniform vec3 emissiveFresnelCenterColor;"),v.push("uniform vec3 emissiveFresnelEdgeColor;"))),v.push("uniform vec4 lightAmbient;"),h)for(b=0,f=a.lights.length;b 0.0) { discard; }"),v.push("}")}if("points"===r.primitiveName&&(v.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),v.push("float r = dot(cxy, cxy);"),v.push("if (r > 1.0) {"),v.push(" discard;"),v.push("}")),v.push("float occlusion = 1.0;"),n.ambient?v.push("vec3 ambientColor = materialAmbient;"):v.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);"),n.diffuse?v.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?v.push("vec3 diffuseColor = materialBaseColor;"):v.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);"),r.colors&&v.push("diffuseColor *= vColor.rgb;"),n.emissive?v.push("vec3 emissiveColor = materialEmissive;"):v.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);"),n.specular?v.push("vec3 specular = materialSpecular;"):v.push("vec3 specular = vec3(1.0, 1.0, 1.0);"),void 0!==n.alpha?v.push("float alpha = materialAlphaModeCutoff[0];"):v.push("float alpha = 1.0;"),r.colors&&v.push("alpha *= vColor.a;"),void 0!==n.glossiness?v.push("float glossiness = materialGlossiness;"):v.push("float glossiness = 1.0;"),void 0!==n.metallic?v.push("float metallic = materialMetallic;"):v.push("float metallic = 1.0;"),void 0!==n.roughness?v.push("float roughness = materialRoughness;"):v.push("float roughness = 1.0;"),void 0!==n.specularF0?v.push("float specularF0 = materialSpecularF0;"):v.push("float specularF0 = 1.0;"),c&&(h&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(v.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),v.push("vec2 textureCoord;")),c&&s._ambientMap&&(s._ambientMap._state.matrix?v.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 ambientTexel = texture2D(ambientMap, textureCoord).rgb;"),v.push("ambientTexel = "+TEXTURE_DECODE_FUNCS[s._ambientMap._state.encoding]+"(ambientTexel);"),v.push("ambientColor *= ambientTexel.rgb;")),c&&s._diffuseMap&&(s._diffuseMap._state.matrix?v.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 diffuseTexel = texture2D(diffuseMap, textureCoord);"),v.push("diffuseTexel = "+TEXTURE_DECODE_FUNCS[s._diffuseMap._state.encoding]+"(diffuseTexel);"),v.push("diffuseColor *= diffuseTexel.rgb;"),v.push("alpha *= diffuseTexel.a;")),c&&s._baseColorMap&&(s._baseColorMap._state.matrix?v.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 baseColorTexel = texture2D(baseColorMap, textureCoord);"),v.push("baseColorTexel = "+TEXTURE_DECODE_FUNCS[s._baseColorMap._state.encoding]+"(baseColorTexel);"),v.push("diffuseColor *= baseColorTexel.rgb;"),v.push("alpha *= baseColorTexel.a;")),c&&s._emissiveMap&&(s._emissiveMap._state.matrix?v.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 emissiveTexel = texture2D(emissiveMap, textureCoord);"),v.push("emissiveTexel = "+TEXTURE_DECODE_FUNCS[s._emissiveMap._state.encoding]+"(emissiveTexel);"),v.push("emissiveColor = emissiveTexel.rgb;")),c&&s._alphaMap&&(s._alphaMap._state.matrix?v.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("alpha *= texture2D(alphaMap, textureCoord).r;")),c&&s._occlusionMap&&(s._occlusionMap._state.matrix?v.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("occlusion *= texture2D(occlusionMap, textureCoord).r;")),h&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){for(c&&s._normalMap?(s._normalMap._state.matrix?v.push("textureCoord = (normalMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):v.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?v.push("textureCoord = (specularMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("specular *= texture2D(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?v.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("glossiness *= texture2D(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?v.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 specGlossRGB = texture2D(materialSpecularGlossinessMap, textureCoord).rgba;"),v.push("specular *= specGlossRGB.rgb;"),v.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?v.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("metallic *= texture2D(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?v.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("roughness *= texture2D(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?v.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec3 metalRoughRGB = texture2D(metallicRoughnessMap, textureCoord).rgb;"),v.push("metallic *= metalRoughRGB.b;"),v.push("roughness *= metalRoughRGB.g;")),v.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(v.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),v.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(v.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),v.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(v.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),v.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(v.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),v.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),v.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),v.push(" discard;"),v.push("}"),v.push("IncidentLight light;"),v.push("Material material;"),v.push("Geometry geometry;"),v.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),v.push("vec3 viewLightDir;"),d&&(v.push("material.diffuseColor = diffuseColor;"),v.push("material.specularColor = specular;"),v.push("material.shine = materialShininess;")),p&&(v.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),v.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),v.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),v.push("material.specularColor = specular;")),u&&(v.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),v.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),v.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),v.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),v.push("geometry.position = vViewPosition;"),a.lightMaps.length>0&&v.push("geometry.worldNormal = normalize(vWorldNormal);"),v.push("geometry.viewNormal = viewNormal;"),v.push("geometry.viewEyeDir = viewEyeDir;"),d&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||u)&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("computePBRLightMapping(geometry, material, reflectedLight);"),v.push("float shadow = 1.0;"),v.push("float shadowAcneRemover = 0.007;"),v.push("vec3 fragmentDepth;"),v.push("float texelSize = 1.0 / 1024.0;"),v.push("float amountInLight = 0.0;"),v.push("vec3 shadowCoord;"),v.push("vec4 rgbaDepth;"),v.push("float depth;"),b=0,f=a.lights.length;b0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function logErrors(e){console.error(e.join("\n"))}class Program{constructor(e,t){this.id=ids$1.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 Shader(e,e.VERTEX_SHADER,joinSansComments(this.source.vertex)),this._fragmentShader=new Shader(e,e.FRAGMENT_SHADER,joinSansComments(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void logErrors(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void logErrors(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void logErrors(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void logErrors(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 logErrors(this.errors);const a=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=r.sectionPlanes.length;h0&&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 EmphasisFillShaderSource{constructor(e){this.vertex=buildVertex(e),this.fragment=buildFragment(e)}}function buildVertex(e){const t=e.scene,i=t._lightsState,s=hasNormals$1(e),r=t._sectionPlanesState.sectionPlanes.length>0,o=!!e._geometry._state.compressGeometry,a=e._state.billboard,n=e._state.stationary,l=[];let h,c,d;if(l.push("// EmphasisFillShaderSource vertex shader"),l.push("attribute 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;"),o&&l.push("uniform mat4 positionsDecodeMatrix;"),r&&l.push("varying vec4 vWorldPosition;"),l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){for(l.push("attribute vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;"),h=0,c=i.lights.length;h= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}if(l.push("varying vec4 vColor;"),"spherical"!==a&&"cylindrical"!==a||(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===a&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),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;"),n&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===a||"cylindrical"===a?(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);"),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(h=0,c=i.lights.length;h0;let r,o;const a=[];if(a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),s)for(a.push("varying vec4 vWorldPosition;"),a.push("uniform bool clippable;"),r=0,o=t.sectionPlanes.length;r 0.0) { discard; }"),a.push("}")}return"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push(" discard;"),a.push("}")),a.push("gl_FragColor = vColor;"),i?a.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):a.push("gl_FragColor = vColor;"),a.push("}"),a}const ids$3=new Map({}),tempVec3a$3=math.vec3(),EmphasisFillRenderer=function(e,t){this.id=ids$3.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new EmphasisFillShaderSource(t),this._allocate(t)},xrayFillRenderers={};EmphasisFillRenderer.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=xrayFillRenderers[t];return i||(i=new EmphasisFillRenderer(t,e),xrayFillRenderers[t]=i,stats.memory.programs++),i._useCount++,i},EmphasisFillRenderer.prototype.put=function(){0==--this._useCount&&(ids$3.removeItem(this.id),this._program&&this._program.destroy(),delete xrayFillRenderers[this._hash],stats.memory.programs--)},EmphasisFillRenderer.prototype.webglContextRestored=function(){this._program=null},EmphasisFillRenderer.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,a=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,n=t._state,l=t._geometry._state,h=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(n.rtcCenterHash,h):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),n.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Edges drawing vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 edgeColor;"),o.push("uniform vec3 offset;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vColor;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===s&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===s||"cylindrical"===s?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; ")),o.push("vColor = edgeColor;"),t&&o.push("vWorldPosition = worldPosition;"),o.push(" gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$1(e){const t=e.scene._sectionPlanesState,i=e.scene.gammaOutput,s=t.sectionPlanes.length>0;let r,o;const a=[];if(a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),s)for(a.push("varying vec4 vWorldPosition;"),a.push("uniform bool clippable;"),r=0,o=t.sectionPlanes.length;r 0.0) { discard; }"),a.push("}")}return a.push("gl_FragColor = vColor;"),i?a.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):a.push("gl_FragColor = vColor;"),a.push("}"),a}const ids$4=new Map({}),tempVec3a$4=math.vec3(),EmphasisEdgesRenderer=function(e,t){this.id=ids$4.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new EmphasisEdgesShaderSource(t),this._allocate(t)},renderers={};EmphasisEdgesRenderer.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=renderers[t];return i||(i=new EmphasisEdgesRenderer(t,e),renderers[t]=i,stats.memory.programs++),i._useCount++,i},EmphasisEdgesRenderer.prototype.put=function(){0==--this._useCount&&(ids$4.removeItem(this.id),this._program&&this._program.destroy(),delete renderers[this._hash],stats.memory.programs--)},EmphasisEdgesRenderer.prototype.webglContextRestored=function(){this._program=null},EmphasisEdgesRenderer.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let a;const n=t._state,l=t._geometry,h=l._state,c=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(n.rtcCenterHash,c):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),n.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Mesh picking vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("varying vec4 vViewPosition;"),o.push("uniform vec3 offset;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===s&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"!==s&&"cylindrical"!==s||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);")),o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),t&&o.push(" vWorldPosition = worldPosition;"),o.push(" gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$2(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Mesh 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"),s.push("uniform vec4 pickColor;"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = pickColor; "),s.push("}"),s}const tempVec3a$5=math.vec3(),PickMeshRenderer=function(e,t){this._hash=e,this._shaderSource=new PickMeshShaderSource(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},renderers$1={};PickMeshRenderer.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=renderers$1[t];if(!i){if((i=new PickMeshRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$1[t]=i,stats.memory.programs++}return i._useCount++,i},PickMeshRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$1[this._hash],stats.memory.programs--)},PickMeshRenderer.prototype.webglContextRestored=function(){this._program=null},PickMeshRenderer.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,a=t._geometry._state,n=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,n?e.getRTCPickViewMatrix(r.rtcCenterHash,n):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,d=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,d/255,c/255,h/255),a.indicesBuf?(s.drawElements(a.primitive,a.indicesBuf.numItems,a.indicesBuf.itemType,0),e.drawElements++):a.positions&&s.drawArrays(s.TRIANGLES,0,a.positions.numItems)},PickMeshRenderer.prototype._allocate=function(e){const t=e.scene.canvas.gl;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e.scene._sectionPlanesState.sectionPlanes.length;t0,i=!!e._geometry._state.compressGeometry,s=(e._state.billboard,e._state.stationary,[]);return s.push("// Surface picking vertex shader"),s.push("attribute vec3 position;"),s.push("attribute vec4 color;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform vec3 offset;"),t&&(s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;")),s.push("varying vec4 vColor;"),i&&s.push("uniform mat4 positionsDecodeMatrix;"),s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;"),s.push(" vec4 worldPosition = modelMatrix * localPosition; "),s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vColor = color;"),s.push(" gl_Position = projMatrix * viewPosition;"),s.push("}"),s}function buildFragment$3(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Surface 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"),s.push("varying vec4 vColor;"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vColor;"),s.push("}"),s}const tempVec3a$6=math.vec3(),PickTriangleRenderer=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new PickTriangleShaderSource(t),this._allocate(t)},renderers$2={};PickTriangleRenderer.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=renderers$2[t];if(!i){if((i=new PickTriangleRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$2[t]=i,stats.memory.programs++}return i._useCount++,i},PickTriangleRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$2[this._hash],stats.memory.programs--)},PickTriangleRenderer.prototype.webglContextRestored=function(){this._program=null},PickTriangleRenderer.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,a=t._geometry,n=t._geometry._state,l=t.rtcCenter,h=o.backfaces,c=o.frontface,d=a._getPickTrianglePositions(),u=a._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.rtcCenterHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Mesh occlusion vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec3 offset;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===s&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"!==s&&"cylindrical"!==s||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);")),o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),t&&o.push(" vWorldPosition = worldPosition;"),o.push(" gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$4(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Mesh 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"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}const tempVec3a$7=math.vec3(),OcclusionRenderer=function(e,t){this._hash=e,this._shaderSource=new OcclusionShaderSource(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},renderers$3={};OcclusionRenderer.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=renderers$3[t];if(!i){if((i=new OcclusionRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$3[t]=i,stats.memory.programs++}return i._useCount++,i},OcclusionRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$3[this._hash],stats.memory.programs--)},OcclusionRenderer.prototype.webglContextRestored=function(){this._program=null},OcclusionRenderer.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,a=t._geometry._state,n=t.rtcCenter;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,n?e.getRTCViewMatrix(o.rtcCenterHash,n):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];return s.push("// Mesh shadow vertex shader"),s.push("attribute 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("varying 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;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}function buildFragment$5(e){const t=e.scene,i=(t.canvas.gl,t._sectionPlanesState),s=i.sectionPlanes.length>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("varying vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("gl_FragColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}const ShadowRenderer=function(e,t){this._hash=e,this._shaderSource=new ShadowShaderSource(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},renderers$4={};ShadowRenderer.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=renderers$4[i];if(!s){if((s=new ShadowRenderer(i,e)).errors)return console.log(s.errors.join("\n")),null;renderers$4[i]=s,stats.memory.programs++}return s._useCount++,s},ShadowRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$4[this._hash],stats.memory.programs--)},ShadowRenderer.prototype.webglContextRestored=function(){this._program=null},ShadowRenderer.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++)},ShadowRenderer.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Program(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;e0){let e,t,r,o,a;for(let n=0,l=this._uSectionPlanes.length;n0)for(let i=0;i-1){const V=L.geometry._state,O=L.scene,j=O.camera,U=O.canvas;if("triangles"===V.primitiveName){k.primitive="triangle";const O=B,G=V.indices,z=V.positions;let H,$,W,X;if(G){var I=G[O+0],F=G[O+1],N=G[O+2];o[0]=I,o[1]=F,o[2]=N,k.indices=o,H=3*I,$=3*F,W=3*N}else W=($=(H=3*O)+3)+3;if(i[0]=z[H+0],i[1]=z[H+1],i[2]=z[H+2],s[0]=z[$+0],s[1]=z[$+1],s[2]=z[$+2],r[0]=z[W+0],r[1]=z[W+1],r[2]=z[W+2],V.compressGeometry){const e=V.positionsDecodeMatrix;e&&(geometryCompressionUtils.decompressPosition(i,e,i),geometryCompressionUtils.decompressPosition(s,e,s),geometryCompressionUtils.decompressPosition(r,e,r))}k.canvasPos?(X=k.canvasPos,math.canvasPosToLocalRay(U.canvas,D,T,L.worldMatrix,X,e,t)):k.origin&&k.direction&&math.worldRayToLocalRay(L.worldMatrix,k.origin,k.direction,e,t),math.normalizeVec3(t),math.rayPlaneIntersect(e,t,i,s,r,a),k.localPos=a,k.position=a,f[0]=a[0],f[1]=a[1],f[2]=a[2],f[3]=1,math.transformVec4(L.worldMatrix,f,g),n[0]=g[0],n[1]=g[1],n[2]=g[2],k.worldPos=n,math.transformVec4(j.matrix,g,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],k.viewPos=l,math.cartesianToBarycentric(a,i,s,r,h),k.bary=h;const Y=V.normals;if(Y){if(V.compressGeometry){const e=3*I,t=3*F,i=3*N;geometryCompressionUtils.decompressNormal(Y.subarray(e,e+2),c),geometryCompressionUtils.decompressNormal(Y.subarray(t,t+2),d),geometryCompressionUtils.decompressNormal(Y.subarray(i,i+2),u)}else c[0]=Y[H],c[1]=Y[H+1],c[2]=Y[H+2],d[0]=Y[$],d[1]=Y[$+1],d[2]=Y[$+2],u[0]=Y[W],u[1]=Y[W+1],u[2]=Y[W+2];const e=math.addVec3(math.addVec3(math.mulVec3Scalar(c,h[0],b),math.mulVec3Scalar(d,h[1],y),M),math.mulVec3Scalar(u,h[2],w),P);k.worldNormal=math.normalizeVec3(math.transformVec3(L.worldNormalMatrix,e,x))}const q=V.uv;if(q){if(p[0]=q[2*I],p[1]=q[2*I+1],m[0]=q[2*F],m[1]=q[2*F+1],_[0]=q[2*N],_[1]=q[2*N+1],V.compressGeometry){const e=V.uvDecodeMatrix;e&&(geometryCompressionUtils.decompressUV(p,e,p),geometryCompressionUtils.decompressUV(m,e,m),geometryCompressionUtils.decompressUV(_,e,_))}k.uv=math.addVec3(math.addVec3(math.mulVec2Scalar(p,h[0],E),math.mulVec2Scalar(m,h[1],A),C),math.mulVec2Scalar(_,h[2],R),S)}}}}}();function buildSphereGeometry(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 a=e.heightSegments||18;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),(a=Math.floor(t*a))<18&&(a=18);let n=e.widthSegments||18;n<0&&(console.error("negative widthSegments not allowed - will invert"),n*=-1),(n=Math.floor(t*n))<18&&(n=18);const l=[],h=[],c=[],d=[];let u,p,m,_,f,g,v,b,y,M,w,P,x,E,A;for(u=0;u<=a;u++)for(m=u*Math.PI/a,_=Math.sin(m),f=Math.cos(m),p=0;p<=n;p++)g=2*p*Math.PI/n,v=Math.sin(g),y=(b=Math.cos(g))*_,M=f,w=v*_,P=1-p/n,x=u/a,h.push(y),h.push(M),h.push(w),c.push(P),c.push(x),l.push(i+o*y),l.push(s+o*M),l.push(r+o*w);for(u=0;u{this._setPos(this._sectionPlane.pos)}),this._onSectionPlaneDir=e.on("dir",()=>{this._setDir(this._sectionPlane.dir)}))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),worldToRTCPos(this._pos,this._rtcCenter,this._rtcPos),this._rootNode.rtcCenter=this._rtcCenter,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=math.vec3PairToQuaternion(zeroVec,e,quat)}setVisible(e=!0){if(this._visible!==e){var t;for(t in this._visible=e,this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].visible=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].visible=e)}}getVisible(){return this._visible}setCulled(e){var t;for(t in this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].culled=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].culled=e)}_createNodes(){const e=this._viewer.scene;this._rootNode=new Node(e,{position:[0,0,0],scale:[5,5,5]});const t=this._rootNode,i={arrowHead:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.01,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.01,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.01,radiusBottom:.01,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},s={pickable:new PhongMaterial(t,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new PhongMaterial(t,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new PhongMaterial(t,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new PhongMaterial(t,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new PhongMaterial(t,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new EmphasisMaterial(t,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,{primitive:"triangles",positions:[.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,.5,-0,.5,-.5,-0,-.5,-.5,-0,-.5,.5,-0],indices:[0,1,2,2,3,0]}),material:new PhongMaterial(t,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new EmphasisMaterial(t,{edges:!1,filled:!0,fillColor:[1,1,0],edgeColor:[0,0,0],fillAlpha:.1,backfaces:!0}),pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),!1),planeFrame:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildTorusGeometry({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new PhongMaterial(t,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new EmphasisMaterial(t,{edges:!1,edgeColor:[0,0,0],filled:!0,fillColor:[.8,.8,.8],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),!1),xCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.red,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,-.07,-.8,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(0*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),xCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,-.8,-.07,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),yCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),yCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(.07,0,-.8,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(.8,0,-.07,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.blue,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurveCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(.8,-.07,0,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4());return math.mulMat4(e,t,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(.05,-.8,0,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),center:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildSphereGeometry({radius:.05})),material:s.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),xAxis:t.addChild(new Mesh(t,{geometry:i.axis,material:s.red,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2}),!1),yShaft:t.addChild(new Mesh(t,{geometry:i.axis,material:s.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yShaftHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zShaft:t.addChild(new Mesh(t,{geometry:i.axis,material:s.blue,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),!1),zAxisHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1}),!1)},this._affordanceMeshes={planeFrame:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildTorusGeometry({center:[0,0,0],radius:2,tube:.01,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new PhongMaterial(t,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new EmphasisMaterial(t,{edges:!1,filled:!0,fillColor:[1,1,0],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,1],rotation:[0,0,45]}),!1),xHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.red,highlighted:!0,highlightMaterial:s.highlightRed,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.green,highlighted:!0,highlightMaterial:s.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.blue,highlighted:!0,highlightMaterial:s.highlightBlue,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.red,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.green,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.blue,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1)}}_bindEvents(){const e=this;var t=!1;const i=-1,s=0,r=1,o=2,a=3,n=4,l=5,h=this._rootNode;var c=null,d=null;const u=math.vec2(),p=math.vec3([1,0,0]),m=math.vec3([0,1,0]),_=math.vec3([0,0,1]),f=this._viewer.scene.canvas.canvas,g=this._viewer.camera,v=this._viewer.scene;{const e=math.vec3([0,0,0]);var b=-1;this._onCameraViewMatrix=v.camera.on("viewMatrix",()=>{}),this._onCameraProjMatrix=v.camera.on("projMatrix",()=>{}),this._onSceneTick=v.on("tick",()=>{var t=Math.abs(math.lenVec3(math.subVec3(v.camera.eye,h.position,e)));if(t!==b){const e=t/50*10;h.scale=[e,e,e],b=t}})}const y=function(){const e=new Float32Array(2);return function(t){if(t){for(var i=t.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-s,e[1]=t.pageY-r}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),M=function(){const t=math.mat4();return function(i,s){return math.quaternionToMat4(e._rootNode.quaternion,t),math.transformVec3(t,i,s),math.normalizeVec3(s),s}}();var w=function(){const e=math.vec3();return function(t){const i=Math.abs(t[0]);return i>Math.abs(t[1])&&i>Math.abs(t[2])?math.cross3Vec3(t,[0,1,0],e):math.cross3Vec3(t,[1,0,0],e),math.cross3Vec3(e,t,e),math.normalizeVec3(e),e}}();const P=function(){const t=math.vec3(),i=math.vec3(),s=math.vec4();return function(r,o,a){M(r,s);const n=w(s,o,a);E(o,n,t),E(a,n,i),math.subVec3(i,t);const l=math.dotVec3(i,s);e._pos[0]+=s[0]*l,e._pos[1]+=s[1]*l,e._pos[2]+=s[2]*l,e._rootNode.position=e._pos,e.sectionPlane&&(e.sectionPlane.pos=e._pos)}}();var x=function(){const t=math.vec4(),i=math.vec4(),s=math.vec4(),r=math.vec4();return function(o,a,n){if(M(o,r),!(E(a,r,t)&&E(n,r,i))){const e=w(r,a,n);E(a,e,t,1),E(n,e,i,1);var l=math.dotVec3(t,r);t[0]-=l*r[0],t[1]-=l*r[1],t[2]-=l*r[2],l=math.dotVec3(i,r),i[0]-=l*r[0],i[1]-=l*r[1],i[2]-=l*r[2]}math.normalizeVec3(t),math.normalizeVec3(i),l=math.dotVec3(t,i),l=math.clamp(l,-1,1);var h=Math.acos(l)*math.RADTODEG;math.cross3Vec3(t,i,s),math.dotVec3(s,r)<0&&(h=-h),e._rootNode.rotate(o,h),A()}}(),E=function(){const t=math.vec4([0,0,0,1]),i=math.mat4();return function(s,r,o,a){a=a||0,t[0]=s[0]/f.width*2-1,t[1]=-(s[1]/f.height*2-1),t[2]=0,t[3]=1,math.mulMat4(g.projMatrix,g.viewMatrix,i),math.inverseMat4(i),math.transformVec4(i,t,t),math.mulVec4Scalar(t,1/t[3]);var n=g.eye;math.subVec4(t,n,t);const l=e._sectionPlane.pos;var h=-math.dotVec3(l,r)-a,c=math.dotVec3(r,t);if(Math.abs(c)>.005){var d=-(math.dotVec3(r,n)+h)/c;return math.mulVec3Scalar(t,d,o),math.addVec3(o,n),math.subVec3(o,l,o),!0}return!1}}();const A=function(){const t=math.vec3(),i=math.mat4();return function(){e.sectionPlane&&(math.quaternionToMat4(h.quaternion,i),math.transformVec3(i,[0,0,1],t),e._sectionPlane.dir=t)}}();var C,R=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",e=>{if(!this._visible)return;if(R)return;var h;switch(t=!1,C&&(C.visible=!1),e.entity.id){case this._displayMeshes.xAxisArrowHandle.id:case this._displayMeshes.xAxisHandle.id:h=this._affordanceMeshes.xAxisArrow,c=s;break;case this._displayMeshes.yAxisArrowHandle.id:case this._displayMeshes.yShaftHandle.id:h=this._affordanceMeshes.yAxisArrow,c=r;break;case this._displayMeshes.zAxisArrowHandle.id:case this._displayMeshes.zAxisHandle.id:h=this._affordanceMeshes.zAxisArrow,c=o;break;case this._displayMeshes.xCurveHandle.id:h=this._affordanceMeshes.xHoop,c=a;break;case this._displayMeshes.yCurveHandle.id:h=this._affordanceMeshes.yHoop,c=n;break;case this._displayMeshes.zCurveHandle.id:h=this._affordanceMeshes.zHoop,c=l;break;default:return void(c=i)}h&&(h.visible=!0),C=h,t=!0}),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOut",e=>{this._visible&&(C&&(C.visible=!1),C=null,c=i)}),f.addEventListener("mousedown",this._canvasMouseDownListener=(e=>{if(e.preventDefault(),this._visible&&t)switch(this._viewer.cameraControl.pointerEnabled=!1,e.which){case 1:R=!0;var i=y(e);d=c,u[0]=i[0],u[1]=i[1]}})),f.addEventListener("mousemove",this._canvasMouseMoveListener=(e=>{if(!this._visible)return;if(!R)return;var t=y(e);const i=t[0],h=t[1];switch(d){case s:P(p,u,t);break;case r:P(m,u,t);break;case o:P(_,u,t);break;case a:x(p,u,t);break;case n:x(m,u,t);break;case l:x(_,u,t)}u[0]=i,u[1]=h})),f.addEventListener("mouseup",this._canvasMouseUpListener=(e=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,R&&(e.which,R=!1,t=!1))})),f.addEventListener("wheel",this._canvasWheelListener=(e=>{if(this._visible)Math.max(-1,Math.min(1,40*-e.deltaY))}))}_destroy(){this._unbindEvents(),this._destroyNodes()}_unbindEvents(){const e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=e.cameraControl;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix),r.off(this._onCameraControlHover),r.off(this._onCameraControlHoverLeave)}_destroyNodes(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}const defaultCSS=".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; } }";class Spinner extends Component{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='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){if(document.getElementById("xeokit-spinner-css"))return;const e=document.createElement("style");e.innerHTML=defaultCSS,e.id="xeokit-spinner-css",document.body.appendChild(e)}_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 WEBGL_CONTEXT_NAMES=["webgl","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Canvas extends Component{get type(){return"Canvas"}constructor(e,t={}){super(e,t),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.canvas.width=this.canvas.clientWidth,this.canvas.height=this.canvas.clientHeight,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=null,r=null,o=null,a=null,n=null,l=null,h=null;this._tick=this.scene.on("tick",function(){const e=i.canvas,t=window.innerWidth!==s||window.innerHeight!==r,c=e.clientWidth!==o||e.clientHeight!==a,d=e.offsetLeft!==n||e.offsetTop!==l,u=e.parentElement;if(t||c||d||u!==h){if(i._spinner._adjustPosition(),c||d){const t=e.clientWidth,s=e.clientHeight;if(c){let t,i=0;for(const e in core.scenes)core.scenes.hasOwnProperty(e)&&(i+=(t=core.scenes[e]).canvas.canvas.clientWidth*t.canvas.canvas.clientHeight);stats.memory.pixels=i,e.width=e.clientWidth,e.height=e.clientHeight}const r=i.boundary;r[0]=e.offsetLeft,r[1]=e.offsetTop,r[2]=t,r[3]=s,i.fire("boundary",r),o=t,a=s}t&&(s=window.innerWidth,r=window.innerHeight),d&&(n=e.offsetLeft,l=e.offsetTop),h=u}}),this._spinner=new Spinner(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId}),this.clearColorAmbient=t.clearColorAmbient}_createCanvas(){const e="xeokit-canvas-"+math.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+='',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-t){i._setVisible(!1);continue}const a=i.canvasPos,n=a[0],l=a[1];n+10<0||l+10<0||n-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=n,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{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.rtcCenter.join();let i=this._occlusionLayers[t];i||(i=new OcclusionLayer(this._scene,e.rtcCenter),this._occlusionLayers[i.rtcCenterHash]=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 void e.error("Marker has not been added to OcclusionTester");const i=e.rtcCenter.join();if(i!==t.rtcCenterHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.rtcCenterHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new OcclusionLayer(this._scene,e.rtcCenter),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.rtcCenter.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.rtcCenterHash],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;e0,t=[];return t.push("// OcclusionTester vertex shader"),t.push("attribute vec3 position;"),t.push("uniform mat4 modelMatrix;"),t.push("uniform mat4 viewMatrix;"),t.push("uniform mat4 projMatrix;"),e&&t.push("varying vec4 vWorldPosition;"),t.push("void main(void) {"),t.push("vec4 worldPosition = vec4(position, 1.0); "),t.push(" vec4 viewPosition = viewMatrix * worldPosition;"),e&&t.push(" vWorldPosition = worldPosition;"),t.push(" gl_Position = projMatrix * viewPosition;"),t.push(" gl_PointSize = "+POINT_SIZE+".0;"),t.push("}"),t}_buildFragmentShaderSource(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,i=[];if(i.push("// OcclusionTester fragment shader"),i.push("precision lowp float;"),t){i.push("varying vec4 vWorldPosition;");for(var s=0;s 0.0) { discard; }")}return i.push(" gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(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;e0){const e=s.sectionPlanes;for(let s=0;s= ( 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 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 \tgl_FragColor = packDepthToRGBA( 1.0- ambientOcclusion );\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 Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.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")}render(e){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",function(){e=!0});const t=math.mat4();return()=>(e&&math.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,a=t.drawingBufferHeight,n=s.camera.project._state,l=n.near,h=n.far,c=n.matrix,d=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;tempVec2[0]=o,tempVec2[1]=a,t.getExtension("OES_standard_derivatives"),t.viewport(0,0,o,a),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,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,d),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale),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,tempVec2),t.uniform1f(this._uRandomSeed,u),i.bindTexture(this._uDepthTexture,e,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)}destroy(){this._program.destroy()}}class SAOBlendRenderer{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._uColorTexture="uColorTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=null,this._aUV=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Program(e,{vertex:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n \n attribute vec3 aPosition;\n attribute vec2 aUV;\n \n varying vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\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 packDepthToRGBA( 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 varying vec2 vUV;\n \n uniform sampler2D uColorTexture;\n uniform sampler2D uOcclusionTexture;\n \n uniform float uOcclusionScale;\n uniform float uOcclusionCutoff;\n \n float unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, unPackFactors );\n }\n \n void main() {\n vec4 color = texture2D(uColorTexture, vUV);\n float ambient = smoothstep(uOcclusionCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, vUV))) * uOcclusionScale;\n gl_FragColor = vec4(color.rgb * (ambient), color.a);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Float32Array([1,1,0,1,0,0,1,0]),s=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._uColorTexture="uColorTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._uOcclusionScale=this._program.getLocation("uOcclusionScale"),this._uOcclusionCutoff=this._program.getLocation("uOcclusionCutoff")}render(e,t){if(this._programError)return;const i=this._scene.canvas.gl,s=this._program,r=i.drawingBufferWidth,o=i.drawingBufferHeight;i.viewport(0,0,r,o),i.clearColor(0,0,0,1),i.disable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT),s.bind(),s.bindTexture(this._uColorTexture,e,0),s.bindTexture(this._uOcclusionTexture,t,2),i.uniform1f(this._uOcclusionScale,1),i.uniform1f(this._uOcclusionCutoff,.01),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}class SAOBlurRenderer{constructor(e){this._scene=e,this._texelOffset=new Float32Array([0,0]),this._program=null,this._programError=!1,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=null,this._aUV=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Program(e,{vertex:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n \n attribute vec3 aPosition;\n attribute vec2 aUV;\n \n varying vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n \n varying vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture;\n \n uniform float uOcclusionScale;\n uniform float uOcclusionCutoff;\n \n uniform vec2 uTexelOffset;\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 float unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, unPackFactors );\n }\n \n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n\n vec4 packDepthToRGBA( 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 void main() {\n \n float centerOcclusion = unpackRGBAToDepth(texture2D(uOcclusionTexture, vUV));\n float centerDepth = unpackRGBAToDepth(texture2D(uDepthTexture, vUV));\n \n float gaussian[5];\n \n gaussian[0] = 0.153170;\n gaussian[1] = 0.144893;\n gaussian[2] = 0.122649;\n gaussian[3] = 0.092902;\n gaussian[4] = 0.062970;\n \n float totalWeight = gaussian[0];\n float sum = centerOcclusion * totalWeight;\n \n for (int r = 1; r <= 4; ++r) {\n \n vec2 uv = vUV + uTexelOffset * float(r) * 2.0;\n \n float occlusionSample = unpackRGBAToDepth(texture2D(uOcclusionTexture, uv));\n float depthSample = unpackRGBAToDepth(texture2D(uDepthTexture, uv));\n \n float weight = gaussian[r];\n weight *= max(0.0, 1.0 - 10.0 * abs(depthSample - centerDepth));\n \n sum += occlusionSample * weight;\n \n totalWeight += weight;\n }\n \n for (int r = 1; r <= 4; ++r) {\n \n vec2 uv = vUV + uTexelOffset * -float(r) * 2.0;\n \n float occlusionSample = unpackRGBAToDepth(texture2D(uOcclusionTexture, uv));\n float depthSample = unpackRGBAToDepth(texture2D(uDepthTexture, uv));\n \n float weight = gaussian[r];\n weight *= max(0.0, 1.0 - 10.0 * abs(depthSample - centerDepth));\n \n sum += occlusionSample * weight;\n \n totalWeight += weight;\n }\n \n float blurredOcclusion = (sum / (totalWeight + 0.0001));\n \n gl_FragColor = packDepthToRGBA(blurredOcclusion);\n \n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Float32Array([1,1,0,1,0,0,1,0]),s=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._uOcclusionScale=this._program.getLocation("uOcclusionScale"),this._uOcclusionCutoff=this._program.getLocation("uOcclusionCutoff"),this._uTexelOffset=this._program.getLocation("uTexelOffset")}render(e,t,i){if(this._programError)return;const s=this._scene.canvas.gl,r=this._program,o=s.drawingBufferWidth,a=s.drawingBufferHeight;0===i?(this._texelOffset[0]=1/o,this._texelOffset[1]=0):(this._texelOffset[0]=0,this._texelOffset[1]=1/a),s.viewport(0,0,o,a),s.clearColor(0,0,0,1),s.disable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT),r.bind(),r.bindTexture(this._uDepthTexture,e,1),r.bindTexture(this._uOcclusionTexture,t,2),s.uniform1f(this._uOcclusionScale,.9),s.uniform1f(this._uOcclusionCutoff,.3),s.uniform2fv(this._uTexelOffset,this._texelOffset),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()}}const Renderer=function(e,t){t=t||{};const i=new FrameContext(e),s=e.canvas.canvas,r=e.canvas.gl,o=!!t.transparent,a=t.alphaDepthMask,n=new Map({});let l={},h={},c=!0,d=!0,u=!0;const p=new RenderBuffer(s,r),m=new RenderBuffer(s,r),_=new RenderBuffer(s,r),f=new RenderBuffer(s,r),g=new RenderBuffer(s,r);let v=!1;const b=new SAOOcclusionRenderer(e),y=new SAOBlurRenderer(e),M=new SAOBlendRenderer(e);function w(){c&&(!function(){for(let e in l)if(l.hasOwnProperty(e)){const t=l[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}}(),c=!1,d=!0),d&&(!function(){for(let e in l)if(l.hasOwnProperty(e)){const t=l[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),d=!1,u=!0),u&&function(){for(let e in l)if(l.hasOwnProperty(e)){const t=l[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e0)for(i.withSAO=!0,A=0;A0)for(A=0;A0)for(A=0;A0)for(A=0;A0||N>0||T>0){if(r.enable(r.CULL_FACE),r.enable(r.BLEND),o?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):(r.blendEquation(r.FUNC_ADD),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA)),i.backfaces=!1,a||r.depthMask(!1),N>0)for(A=0;A0)for(A=0;A0)for(A=0;A0)for(A=0;A0||O>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),O>0)for(A=0;A0)for(A=0;A0||U>0||V>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),o?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),U>0)for(A=0;A0)for(A=0;A0||z>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),z>0)for(A=0;A0)for(A=0;A0||$>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),o?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),$>0)for(A=0;A<$;A++)w[A].drawSelectedEdgesTransparent(i);if(H>0)for(A=0;A{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),document.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:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownLeft=!1,this.mouseDownRight=!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:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}})),this.element.addEventListener("mousemove",this._mouseMoveListener=(e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("mousemove",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault())})),this.element.addEventListener("wheel",this._mouseWheelListener=((e,t)=>{if(!this.enabled)return;const i=Math.max(-1,Math.min(1,40*-e.deltaY));this.fire("mousewheel",i,!0)}),{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)})}{const e={"landscape-primary":90,"landscape-secondary":-90,"portrait-secondary":180,"portrait-primary":0};let t,i;const s=math.vec3(),r=math.vec3(),o={orientation:null,orientationAngle:0},a={orientationAngle:0,acceleration:null,accelerationIncludingGravity:r,rotationRate:math.vec3(),interval:0},n={alpha:0,beta:0,gamma:0,absolute:!1};window.OrientationChangeEvent&&window.addEventListener("orientationchange",this._orientationchangedListener=(()=>{t=window.screen.orientation||window.screen.mozOrientation||window.msOrientation||null,i=t&&e[t]||0,o.orientation=t,o.orientationAngle=i,this.fire("orientationchange",o)}),!1),window.DeviceMotionEvent&&window.addEventListener("devicemotion",this._deviceMotionListener=(e=>{a.interval=e.interval,a.orientationAngle=i;const t=e.acceleration;t?(s[0]=t.x,s[1]=t.y,s[2]=t.z,a.acceleration=s):a.acceleration=null;const o=e.accelerationIncludingGravity;o?(r[0]=o.x,r[1]=o.y,r[2]=o.z,a.accelerationIncludingGravity=r):a.accelerationIncludingGravity=null,a.rotationRate=e.rotationRate,this.fire("devicemotion",a)}),!1),window.DeviceOrientationEvent&&window.addEventListener("deviceorientation",this._deviceOrientListener=(e=>{n.gamma=e.gamma,n.beta=e.beta,n.alpha=e.alpha,n.absolute=e.absolute,this.fire("deviceorientation",n)}),!1)}this._eventsBound=!0}}_unbindEvents(){this._eventsBound&&(document.removeEventListener("keydown",this._keyDownListener),document.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}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 Viewport extends Component{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new RenderState({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 Perspective extends Component{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:2e3}),this._dirty=!1,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.viewport.boundary,t=e[2]/e[3];let i=this._fov;const s=this._fovAxis;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),math.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set fov(e){this._fov=void 0!==e&&null!==e?e:60,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=void 0!==e&&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=void 0!==e&&null!==e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}destroy(){super.destroy(),this._state.destroy(),super.destroy(),this.scene.canvas.off(this._canvasResized)}}class Ortho extends Component{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:2e3}),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.viewport.boundary,s=i[2],r=i[3],o=s/r;let a,n,l,h;s>r?(a=-t,n=t,l=t/o,h=-t/o):(a=-t*o,n=t*o,l=t,h=-t),math.orthoMat4c(a,n,h,l,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){void 0!==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=void 0!==e&&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=void 0!==e&&null!==e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class Frustum extends Component{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,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(){math.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=void 0!==e&&null!==e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=void 0!==e&&null!==e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=void 0!==e&&null!==e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=void 0!==e&&null!==e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=void 0!==e&&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=void 0!==e&&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}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class CustomProjection extends Component{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4()}),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.glRedraw(),this.fire("far",this._state.matrix)}get matrix(){return this._state.matrix}destroy(){super.destroy(),this._state.destroy()}}const tempVec3$1=math.vec3(),tempVec3b=math.vec3(),tempVec3c=math.vec3(),tempVec3d=math.vec3(),tempVec3e=math.vec3(),tempVec3f=math.vec3(),tempMat=math.mat4(),tempMatb=math.mat4(),eyeLookVec=math.vec3(),eyeLookVecNorm=math.vec3(),eyeLookOffset=math.vec3(),offsetEye=math.vec3();class Camera extends Component{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new RenderState({deviceMatrix:math.mat4(),hasDeviceMatrix:!1,matrix:math.mat4(),normalMatrix:math.mat4()}),this._perspective=new Perspective(this),this._ortho=new Ortho(this),this._frustum=new Frustum(this),this._customProjection=new CustomProjection(this),this._project=this._perspective,this._eye=math.vec3([0,0,10]),this._look=math.vec3([0,0,0]),this._up=math.vec3([0,1,0]),this._worldUp=math.vec3([0,1,0]),this._worldRight=math.vec3([1,0,0]),this._worldForward=math.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?(math.subVec3(this._eye,this._look,eyeLookVec),math.normalizeVec3(eyeLookVec,eyeLookVecNorm),math.mulVec3Scalar(eyeLookVecNorm,1e3,eyeLookOffset),math.addVec3(this._look,eyeLookOffset,offsetEye),t=offsetEye):t=this._eye,e.hasDeviceMatrix?(math.lookAtMat4v(t,this._look,this._up,tempMatb),math.mulMat4(e.deviceMatrix,tempMatb,e.matrix)):math.lookAtMat4v(t,this._look,this._up,e.matrix),math.inverseMat4(this._state.matrix,this._state.normalMatrix),math.transposeMat4(this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=math.subVec3(this._eye,this._look,tempVec3$1);math.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tempMat),t=math.transformPoint3(tempMat,t,tempVec3b),this.eye=math.addVec3(this._look,t,tempVec3c),this.up=math.transformPoint3(tempMat,this._up,tempVec3d)}orbitPitch(e){if(this._constrainPitch&&(e=math.dotVec3(this._up,this._worldUp)/math.DEGTORAD)<1)return;let t=math.subVec3(this._eye,this._look,tempVec3$1);const i=math.cross3Vec3(math.normalizeVec3(t,tempVec3b),math.normalizeVec3(this._up,tempVec3c));math.rotationMat4v(.0174532925*e,i,tempMat),t=math.transformPoint3(tempMat,t,tempVec3d),this.up=math.transformPoint3(tempMat,this._up,tempVec3e),this.eye=math.addVec3(t,this._look,tempVec3f)}yaw(e){let t=math.subVec3(this._look,this._eye,tempVec3$1);math.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tempMat),t=math.transformPoint3(tempMat,t,tempVec3b),this.look=math.addVec3(t,this._eye,tempVec3c),this._gimbalLock&&(this.up=math.transformPoint3(tempMat,this._up,tempVec3d))}pitch(e){if(this._constrainPitch&&(e=math.dotVec3(this._up,this._worldUp)/math.DEGTORAD)<1)return;let t=math.subVec3(this._look,this._eye,tempVec3$1);const i=math.cross3Vec3(math.normalizeVec3(t,tempVec3b),math.normalizeVec3(this._up,tempVec3c));math.rotationMat4v(.0174532925*e,i,tempMat),this.up=math.transformPoint3(tempMat,this._up,tempVec3f),t=math.transformPoint3(tempMat,t,tempVec3d),this.look=math.addVec3(t,this._eye,tempVec3e)}pan(e){const t=math.subVec3(this._eye,this._look,tempVec3$1),i=[0,0,0];let s;if(0!==e[0]){const r=math.cross3Vec3(math.normalizeVec3(t,[]),math.normalizeVec3(this._up,tempVec3b));s=math.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=math.mulVec3Scalar(math.normalizeVec3(this._up,tempVec3c),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=math.mulVec3Scalar(math.normalizeVec3(t,tempVec3d),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=math.addVec3(this._eye,i,tempVec3e),this.look=math.addVec3(this._look,i,tempVec3f)}zoom(e){const t=math.subVec3(this._eye,this._look,tempVec3$1),i=Math.abs(math.lenVec3(t,tempVec3b)),s=Math.abs(i+e);if(s<.5)return;const r=math.normalizeVec3(t,tempVec3c);this.eye=math.addVec3(this._look,math.mulVec3Scalar(r,s),tempVec3d)}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=math.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 math.lenVec3(math.subVec3(this._look,this._eye,tempVec3$1))}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 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}destroy(){super.destroy(),this._state.destroy()}}class Light extends Component{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class DirLight extends Light{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 RenderState({type:"dir",dir:math.vec3([1,1,1]),color:math.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=math.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];math.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=math.identityMat4()),math.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new RenderBuffer(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class AmbientLight extends Light{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:math.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()}}function buildBoxGeometry(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,a=r?r[1]:0,n=r?r[2]:0,l=-t+o,h=-i+a,c=-s+n,d=t+o,u=i+a,p=s+n;return utils.apply(e,{positions:[d,u,p,l,u,p,l,h,p,d,h,p,d,u,p,d,h,p,d,h,c,d,u,c,d,u,p,d,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,d,h,c,d,h,p,l,h,p,d,h,c,l,h,c,l,u,c,d,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]})}const PRESETS$1={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 EdgeMaterial extends Material{get type(){return"EdgeMaterial"}get presets(){return PRESETS$1}constructor(e,t={}){super(e,t),this._state=new RenderState({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=void 0!==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=PRESETS$1[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(PRESETS$1).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const unitsInfo={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 Metrics extends Component{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=math.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return unitsInfo}set units(e){e||(e="meters"),unitsInfo[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=math.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=math.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 SAO extends Component{constructor(e,t={}){super(e,t),this._supported=WEBGL_INFO.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.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.scene._needRecompile=!0,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){void 0!==e&&null!==e||(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){void 0!==e&&null!==e||(e=.2),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){void 0!==e&&null!==e||(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){void 0!==e&&null!==e||(e=500),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){void 0!==e&&null!==e||(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){void 0!==e&&null!==e||(e=.2),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){void 0!==e&&null!==e||(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}function getEntityIDMap(e,t){const i={};let s,r;for(let o=0,a=t.length;o{this.glRedraw()}),this.canvas.on("webglContextFailed",()=>{alert("xeokit failed to find WebGL!")}),this._renderer=new Renderer(this,{transparent:i,alphaDepthMask:s}),this._sectionPlanesState=new function(){this.sectionPlanes=[];let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";let i;const s=[];for(let e=0,r=t.length;e0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join("")},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{this._renderer.imageDirty()})}_initDefaults(){let e;e=this.geometry,e=this.material,e=this.xrayMaterial,e=this.edgeMaterial,e=this.selectedMaterial,e=this.highlightMaterial}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+utils.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=math.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],utils.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])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!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}_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){delete this.models[e.id],this._modelIds=null}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(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}_objectSelectedUpdated(e){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(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}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&core.runTasks();const t={sceneId:null,pass:0};this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),h=!0}h||(t=-100,i=-100,s=-100,r=100,o=100,a=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=getEntityIDMap(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=getEntityIDMap(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity.fire&&t.entity.fire("picked",t),t):void 0}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{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>a&&(a=l[4]),l[5]>n&&(n=l[5]),t=!0}}),t){const e=math.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=a,e[5]=n,e}return this.aabb}setObjectsVisible(e,t){return this._withEntities(e,this.objects,e=>{const i=e.visible!==t;return e.visible=t,i})}setObjectsCollidable(e,t){return this._withEntities(e,this.objects,e=>{const i=e.collidable!==t;return e.collidable=t,i})}setObjectsCulled(e,t){return this._withEntities(e,this.objects,e=>{const i=e.culled!==t;return e.culled=t,i})}setObjectsSelected(e,t){return this._withEntities(e,this.objects,e=>{const i=e.selected!==t;return e.selected=t,i})}setObjectsHighlighted(e,t){return this._withEntities(e,this.objects,e=>{const i=e.highlighted!==t;return e.highlighted=t,i})}setObjectsXRayed(e,t){return this._withEntities(e,this.objects,e=>{const i=e.xrayed!==t;return e.xrayed=t,i})}setObjectsEdges(e,t){return this._withEntities(e,this.objects,e=>{const i=e.edges!==t;return e.edges=t,i})}setObjectsColorized(e,t){return this._withEntities(e,this.objects,e=>{e.colorize=t})}setObjectsOpacity(e,t){return this._withEntities(e,this.objects,e=>{const i=e.opacity!==t;return e.opacity=t,i})}setObjectsPickable(e,t){return this._withEntities(e,this.objects,e=>{const i=e.pickable!==t;return e.pickable=t,i})}setObjectsOffset(e,t){this._withEntities(e,this.objects,e=>{e.offset=t})}_withEntities(e,t,i){utils.isString(e)&&(e=[e]);let s=!1;for(let r=0,o=e.length;r{const o=this._sectionPlane.scene.center,a=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];math.subVec3(o,this._sectionPlane.pos,e);const n=-math.dotVec3(a,e);math.normalizeVec3(a),math.mulVec3Scalar(a,n,t);const l=math.vec3PairToQuaternion(i,this._sectionPlane.dir,s);r[0]=.1*t[0],r[1]=.1*t[1],r[2]=.1*t[2],this._mesh.quaternion=l,this._mesh.position=r};this._onSectionPlanePos=this._sectionPlane.on("pos",o),this._onSectionPlaneDir=this._sectionPlane.on("dir",o)}this._highlighted=!1,this._selected=!1}setHighlighted(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}getHighlighted(){return this._highlighted}setSelected(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}getSelected(){return this._selected}destroy(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}class Overview{constructor(e,t){if(!(t.onHoverEnterPlane&&t.onHoverLeavePlane&&t.onClickedNothing&&t.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=e,this._viewer=e.viewer,this._onHoverEnterPlane=t.onHoverEnterPlane,this._onHoverLeavePlane=t.onHoverLeavePlane,this._onClickedNothing=t.onClickedNothing,this._onClickedPlane=t.onClickedPlane,this._visible=!0,this._planes={},this._canvas=t.overviewCanvas,this._scene=new Scene({canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new DirLight(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new DirLight(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new DirLight(this._scene,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._scene.camera,this._scene.camera.perspective.fov=70,this._zUp=!1;{const e=this._scene.camera,t=math.rotationMat4c(-90*math.DEGTORAD,1,0,0),i=math.vec3(),s=math.vec3(),r=math.vec3();this._synchCamera=(()=>{const o=this._viewer.camera.eye,a=this._viewer.camera.look,n=this._viewer.camera.up;math.mulVec3Scalar(math.normalizeVec3(math.subVec3(o,a,i)),7),this._zUp?(math.transformVec3(t,i,s),math.transformVec3(t,n,r),e.look=[0,0,0],e.eye=math.transformVec3(t,i,s),e.up=math.transformPoint3(t,n,r)):(e.look=[0,0,0],e.eye=i,e.up=n)})}this._onViewerCameraMatrix=this._viewer.camera.on("matrix",this._synchCamera),this._onViewerCameraWorldAxis=this._viewer.camera.on("worldAxis",this._synchCamera),this._onViewerCameraFOV=this._viewer.camera.perspective.on("fov",e=>{this._scene.camera.perspective.fov=e}),this._onViewerCameraProjection=this._viewer.camera.on("projection",e=>{this._scene.camera.projection=e});var i=null;this._onInputMouseMove=this._scene.input.on("mousemove",e=>{const t=this._scene.pick({canvasPos:e});if(t){if(!i||t.entity.id!==i.id){if(i){this._planes[i.id]&&this._onHoverLeavePlane(i.id)}i=t.entity,this._planes[i.id]&&this._onHoverEnterPlane(i.id)}}else i&&(this._onHoverLeavePlane(i.id),i=null)}),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=(()=>{if(i){this._planes[i.id]&&this._onClickedPlane(i.id)}else this._onClickedNothing()})),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=(()=>{i&&(this._onHoverLeavePlane(i.id),i=null)})),this.setVisible(t.overviewVisible)}addSectionPlane(e){this._planes[e.id]=new Plane(this,this._scene,e)}setPlaneHighlighted(e,t){const i=this._planes[e];i&&i.setHighlighted(t)}setPlaneSelected(e,t){const i=this._planes[e];i&&i.setSelected(t)}removeSectionPlane(e){const t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}setVisible(e=!0){this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}getVisible(){return this._visible}destroy(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),this._viewer.camera.off(this._onViewerCameraProjection),this._scene.input.off(this._onInputMouseMove),this._scene.canvas.canvas.removeEventListener("mouseup",this._onCanvasMouseUp),this._scene.canvas.canvas.removeEventListener("mouseout",this._onCanvasMouseOut),this._scene.destroy()}}const tempAABB$1=math.AABB3(),tempVec3$2=math.vec3();class SectionPlanesPlugin extends Plugin{constructor(e,t={}){if(super("SectionPlanes",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new Overview(this,{overviewCanvas:e,visible:t.overviewVisible,onHoverEnterPlane:e=>{this._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:e=>{this._overview.setPlaneHighlighted(e,!1)},onClickedPlane:e=>{if(this.getShownControl()===e)return void this.hideControl();this.showControl(e);const t=this.sectionPlanes[e].pos;tempAABB$1.set(this.viewer.scene.aabb),math.getAABB3Center(tempAABB$1,tempVec3$2),tempAABB$1[0]+=t[0]-tempVec3$2[0],tempAABB$1[1]+=t[1]-tempVec3$2[1],tempAABB$1[2]+=t[2]-tempVec3$2[2],tempAABB$1[3]+=t[0]-tempVec3$2[0],tempAABB$1[4]+=t[1]-tempVec3$2[1],tempAABB$1[5]+=t[2]-tempVec3$2[2],this.viewer.cameraFlight.flyTo({aabb:tempAABB$1,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.error("Can't find overview canvas: '"+t.overviewCanvasId+"' - will create plugin without overview")}else this.error("Config missing: overviewCanvasId - will create plugin without overview");this._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",e=>{this._sectionPlaneCreated(e)})}setOverviewVisible(e){this._overview&&this._overview.setVisible(e)}getOverviewVisible(){if(this._overview)return this._overview.getVisible()}get sectionPlanes(){return this._sectionPlanes}createSectionPlane(e={}){return void 0!==e.id&&null!==e.id&&this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),new SectionPlane(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0})}_sectionPlaneCreated(e){const t=this._freeControls.length>0?this._freeControls.pop():new Control(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",()=>{this._sectionPlaneDestroyed(e)})}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}showControl(e){const t=this._controls[e];t?(this.hideControl(),t.setVisible(!0),this._overview&&this._overview.setPlaneSelected(e,!0),this._shownControlId=e):this.error("Control not found: "+e)}getShownControl(){return this._shownControlId}hideControl(){for(var e in this._controls)this._controls.hasOwnProperty(e)&&(this._controls[e].setVisible(!1),this._overview&&this._overview.setPlaneSelected(e,!1));this._shownControlId=null}destroySectionPlane(e){var t=this.viewer.scene.sectionPlanes[e];t?(this._sectionPlaneDestroyed(t),t.destroy(),e===this._shownControlId&&(this._shownControlId=null)):this.error("SectionPlane not found: "+e)}_sectionPlaneDestroyed(e){this._overview&&this._overview.removeSectionPlane(e);const t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}clear(){const e=Object.keys(this._sectionPlanes);for(var t=0,i=e.length;t{e.target.classList.contains("xeokit-context-menu-item")||this.hide()}),e.items&&(this.items=e.items),this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}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{const i=this._getNextId(),s=new Menu(i);for(let i=0,r=e.length;i0,l=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),d=i.getEnabled||(()=>!0),u=new Item(l,h,c,d);if(u.parentMenu=s,o.items.push(u),n){const e=t(a);u.subMenu=e,e.parentItem=u}this._itemList.push(u),this._itemMap[u.id]=u}}return this._menuList.push(s),this._menuMap[s.id]=s,s};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+" [MORE]"):i.push('
  • '+l+"
  • ")}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=(e=>{e.preventDefault()});const o=this;let a=null;if(t)for(let e=0,i=t.length;e{if(e.preventDefault(),!1===t.enabled)return;const i=t.subMenu;if(!i)return void(a&&(o._hideMenu(a.id),a=null));a&&a.id!==i.id&&(o._hideMenu(a.id),a=null);const s=t.itemElement,r=i.menuElement,n=s.getBoundingClientRect();r.getBoundingClientRect();n.right+200>window.innerWidth?o._showMenu(i.id,n.left-200,n.top-1):o._showMenu(i.id,n.right-5,n.top-1),a=i}),s||(t.itemElement.addEventListener("click",e=>{e.preventDefault(),o.hide(),o._context&&!1!==t.enabled&&t.doAction&&t.doAction(o._context)}),t.itemElement.addEventListener("mouseenter",e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)}))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}const tempAABB$2=math.AABB3(),tempVec3$3=math.vec3();class SectionToolContextMenu extends ContextMenu{constructor(e={}){if(!e.sectionPlanesPlugin)throw"Missing config: sectionPlanesPlugin";super(utils.apply({},e)),this._sectionPlanesPlugin=e.sectionPlanesPlugin,this._viewer=this._sectionPlanesPlugin.viewer,this._onSceneSectionPlaneCreated=this._viewer.scene.on("sectionPlaneCreated",()=>{this._buildMenu()}),this._onSceneSectionPlaneDestroyed=this._viewer.scene.on("sectionPlaneDestroyed",()=>{this._buildMenu()}),this._buildMenu()}_buildMenu(){const e=this._sectionPlanesPlugin,t=Object.values(e.sectionPlanes),i=[];for(let s=0,r=t.length;s"Slice #"+(s+1),doHoverEnter(t){e.hideControl(),e.showControl(r.id)},doHoverLeave(t){e.hideControl()},items:[[{getTitle:e=>"Edit",doAction:t=>{e.hideControl(),e.showControl(r.id);const i=r.pos;tempAABB$2.set(this._viewer.scene.aabb),math.getAABB3Center(tempAABB$2,tempVec3$3),tempAABB$2[0]+=i[0]-tempVec3$3[0],tempAABB$2[1]+=i[1]-tempVec3$3[1],tempAABB$2[2]+=i[2]-tempVec3$3[2],tempAABB$2[3]+=i[0]-tempVec3$3[0],tempAABB$2[4]+=i[1]-tempVec3$3[1],tempAABB$2[5]+=i[2]-tempVec3$3[2],this._viewer.cameraFlight.flyTo({aabb:tempAABB$2,fitFOV:65})}},{getTitle:e=>"Flip",doAction:e=>{r.flipDir()}},{getTitle:e=>"Delete",doAction:e=>{r.destroy()}}]]})}this.items=[[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}},{title:"Flip Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.flipSections()}}],i]}destroy(){super.destroy();const e=this._viewer.scene;e.off(this._onSceneSectionPlaneCreated),e.off(this._onSceneSectionPlaneDestroyed)}}class SectionTool extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";if(!t.menuButtonElement)throw"Missing config: menuButtonElement";this._buttonElement=t.buttonElement,this._counterElement=t.counterElement,this._menuButtonElement=t.menuButtonElement,this._menuButtonArrowElement=t.menuButtonArrowElement,this._sectionPlanesPlugin=new SectionPlanesPlugin(this.viewer,{}),this._sectionToolContextMenu=new SectionToolContextMenu({sectionPlanesPlugin:this._sectionPlanesPlugin,hideOnMouseDown:!1}),this._sectionPlanesPlugin.setOverviewVisible(!1),this.on("enabled",e=>{e?(this._buttonElement.classList.remove("disabled"),this._counterElement&&this._counterElement.classList.remove("disabled"),this._menuButtonElement.classList.remove("disabled"),this._menuButtonArrowElement.classList.remove("disabled")):(this._buttonElement.classList.add("disabled"),this._counterElement&&this._counterElement.classList.add("disabled"),this._menuButtonElement.classList.add("disabled"),this._menuButtonArrowElement.classList.add("disabled"))}),this.on("active",e=>{e?(this._buttonElement.classList.add("active"),this._counterElement&&this._counterElement.classList.add("active"),this._menuButtonElement.classList.add("active"),this._menuButtonArrowElement.classList.add("active")):(this._buttonElement.classList.remove("active"),this._counterElement&&this._counterElement.classList.remove("active"),this._menuButtonElement.classList.remove("active"),this._menuButtonArrowElement.classList.remove("active"))}),this.on("active",e=>{e||this._sectionPlanesPlugin.hideControl()}),this._buttonElement.addEventListener("click",e=>{if(!this.getEnabled())return;if(e.target===this._menuButtonElement||e.target.parentNode===this._menuButtonElement)return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),document.addEventListener("mousedown",e=>{if(!e.target.classList.contains("xeokit-context-menu-item"))if(e.target===this._menuButtonElement||e.target.parentNode===this._menuButtonElement)if(e.preventDefault(),this._sectionToolContextMenu.shown)this._sectionToolContextMenu.hide();else{this._sectionToolContextMenu.context={bimViewer:this.bimViewer,viewer:this.viewer,sectionTool:this};const e=this._menuButtonElement.getBoundingClientRect();this._sectionToolContextMenu.show(e.left,e.bottom+5)}else this._sectionToolContextMenu.hide()}),this._sectionToolContextMenu.on("shown",()=>{this._menuButtonArrowElement.classList.remove("xeokit-arrow-down"),this._menuButtonArrowElement.classList.add("xeokit-arrow-up")}),this._sectionToolContextMenu.on("hidden",()=>{this._menuButtonArrowElement.classList.remove("xeokit-arrow-up"),this._menuButtonArrowElement.classList.add("xeokit-arrow-down")}),this.bimViewer.on("reset",()=>{this.clear(),this.setActive(!1)}),this._initSectionMode()}_initSectionMode(){this.viewer.scene.input.on("mouseclicked",e=>{if(!this.getActive()||!this.getEnabled())return;const t=this.viewer.scene.pick({canvasPos:e,pickSurface:!0});if(t){const e=this._sectionPlanesPlugin.createSectionPlane({pos:t.worldPos,dir:math.mulVec3Scalar(t.worldNormal,-1)});e.on("destroyed",()=>{this._updateSectionPlanesCount()}),this._sectionPlanesPlugin.showControl(e.id),this._updateSectionPlanesCount()}}),this._updateSectionPlanesCount()}_updateSectionPlanesCount(){this._counterElement&&(this._counterElement.innerText=""+this.getNumSections())}getNumSections(){return Object.keys(this._sectionPlanesPlugin.sectionPlanes).length}clear(){this._sectionPlanesPlugin.clear(),this._updateSectionPlanesCount()}flipSections(){this._sectionPlanesPlugin.flipSectionPlanes()}destroy(){this._sectionPlanesPlugin.destroy(),this._sectionToolContextMenu.destroy(),super.destroy()}}const webglEnums={funcAdd:"FUNC_ADD",funcSubtract:"FUNC_SUBTRACT",funcReverseSubtract:"FUNC_REVERSE_SUBTRACT",zero:"ZERO",one:"ONE",srcColor:"SRC_COLOR",oneMinusSrcColor:"ONE_MINUS_SRC_COLOR",dstColor:"DST_COLOR",oneMinusDstColor:"ONE_MINUS_DST_COLOR",srcAlpha:"SRC_ALPHA",oneMinusSrcAlpha:"ONE_MINUS_SRC_ALPHA",dstAlpha:"DST_ALPHA",oneMinusDstAlpha:"ONE_MINUS_DST_ALPHA",contantColor:"CONSTANT_COLOR",oneMinusConstantColor:"ONE_MINUS_CONSTANT_COLOR",constantAlpha:"CONSTANT_ALPHA",oneMinusConstantAlpha:"ONE_MINUS_CONSTANT_ALPHA",srcAlphaSaturate:"SRC_ALPHA_SATURATE",front:"FRONT",back:"BACK",frontAndBack:"FRONT_AND_BACK",never:"NEVER",less:"LESS",equal:"EQUAL",lequal:"LEQUAL",greater:"GREATER",notequal:"NOTEQUAL",gequal:"GEQUAL",always:"ALWAYS",cw:"CW",ccw:"CCW",linear:"LINEAR",nearest:"NEAREST",linearMipmapNearest:"LINEAR_MIPMAP_NEAREST",nearestMipmapNearest:"NEAREST_MIPMAP_NEAREST",nearestMipmapLinear:"NEAREST_MIPMAP_LINEAR",linearMipmapLinear:"LINEAR_MIPMAP_LINEAR",repeat:"REPEAT",clampToEdge:"CLAMP_TO_EDGE",mirroredRepeat:"MIRRORED_REPEAT",alpha:"ALPHA",rgb:"RGB",rgba:"RGBA",luminance:"LUMINANCE",luminanceAlpha:"LUMINANCE_ALPHA",textureBinding2D:"TEXTURE_BINDING_2D",textureBindingCubeMap:"TEXTURE_BINDING_CUBE_MAP",compareRToTexture:"COMPARE_R_TO_TEXTURE",unsignedByte:"UNSIGNED_BYTE"};function getGLEnum(e,t,i){if(void 0===t)return i;const s=webglEnums[t];return void 0===s?i:e[s]}const color$1=new Uint8Array([0,0,0,1]);class Texture2D{constructor(e,t){this.gl=e,this.target=t||e.TEXTURE_2D,this.texture=e.createTexture(),this.setPreloadColor([0,0,0,0]),this.allocated=!0}setPreloadColor(e){e?(color$1[0]=Math.floor(255*e[0]),color$1[1]=Math.floor(255*e[1]),color$1[2]=Math.floor(255*e[2]),color$1[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(color$1[0]=0,color$1[1]=0,color$1[2]=0,color$1[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,t.NEAREST),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>t;return e+1}class Texture extends Component{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new RenderState({texture:new Texture2D(this.scene.canvas.gl),matrix:math.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=math.vec2([0,0]),this._scale=math.vec2([1,1]),this._rotate=math.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),stats.memory.textures++}_checkMinFilter(e){return"linear"!==(e=e||"linearMipmapLinear")&&"linearMipmapNearest"!==e&&"linearMipmapLinear"!==e&&"nearestMipmapLinear"!==e&&"nearestMipmapNearest"!==e&&(this.error("Unsupported value for 'minFilter': '"+e+"' - supported values are 'linear', 'linearMipmapNearest', 'nearestMipmapNearest', 'nearestMipmapLinear' and 'linearMipmapLinear'. Defaulting to 'linearMipmapLinear'."),e="linearMipmapLinear"),e}_checkMagFilter(e){return"linear"!==(e=e||"linear")&&"nearest"!==e&&(this.error("Unsupported value for 'magFilter': '"+e+"' - supported values are 'linear' and 'nearest'. Defaulting to 'linear'."),e="linear"),e}_checkFilter(e){return"linear"!==(e=e||"linear")&&"nearest"!==e&&(this.error("Unsupported value for 'magFilter': '"+e+"' - supported values are 'linear' and 'nearest'. Defaulting to 'linear'."),e="linear"),e}_checkWrapS(e){return"clampToEdge"!==(e=e||"repeat")&&"mirroredRepeat"!==e&&"repeat"!==e&&(this.error("Unsupported value for 'wrapS': '"+e+"' - supported values are 'clampToEdge', 'mirroredRepeat' and 'repeat'. Defaulting to 'repeat'."),e="repeat"),e}_checkWrapT(e){return"clampToEdge"!==(e=e||"repeat")&&"mirroredRepeat"!==e&&"repeat"!==e&&(this.error("Unsupported value for 'wrapT': '"+e+"' - supported values are 'clampToEdge', 'mirroredRepeat' and 'repeat'. Defaulting to 'repeat'."),e="repeat"),e}_checkFlipY(e){return!!e}_checkEncoding(e){return"linear"!==(e=e||"linear")&&"sRGB"!==e&&"gamma"!==e&&(this.error("Unsupported value for 'encoding': '"+e+"' - supported values are 'linear', 'sRGB', 'gamma'. Defaulting to 'linear'."),e="linear"),e}_webglContextRestored(){this._state.texture=new Texture2D(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=math.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=math.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?math.mulMat4(t,i):i),0!==this._rotate&&(i=math.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?math.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=ensureImageSizePowerOfTwo(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._state.texture.setProps(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=ensureImageSizePowerOfTwo(i),t._state.texture.setImage(i,t._state),t._state.texture.setProps(t._state),t.scene.loading--,t.scene.canvas.spinner.processes--,t.glRedraw()},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(),stats.memory.textures--}}function CubeTextureCanvas(e,t={}){const i="lightgrey",s=t.hoverColor||"rgba(0,0,0,0.4)";var r=500+500/3,o=r/24;const a=[{boundary:[6,6,6,6],color:t.frontColor||t.color||"#55FF55"},{boundary:[18,6,6,6],color:t.backColor||t.color||"#55FF55"},{boundary:[12,6,6,6],color:t.leftColor||t.color||"#FF5555"},{boundary:[0,6,6,6],color:t.rightColor||t.color||"#FF5555"},{boundary:[6,0,6,6],color:t.topColor||t.color||"#7777FF"},{boundary:[6,12,6,6],color:t.bottomColor||t.color||"#7777FF"}],n=[{label:"front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"bottom",boundaries:[[7,13,4,4]],dir:[0,0,1],up:[0,-1,0]},{boundaries:[[7,5,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,0,-1],up:[1,0,1]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,-1],up:[0,-1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,0,-1],up:[-1,0,1]},{boundaries:[[7,11,4,2]],dir:[0,1,1],up:[0,-1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,0,1],up:[-1,0,1]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,0,1],up:[1,0,1]},{boundaries:[[5,7,2,4]],dir:[1,1,0],up:[0,0,1]},{boundaries:[[11,7,2,4]],dir:[-1,1,0],up:[0,0,1]},{boundaries:[[17,7,2,4]],dir:[-1,-1,0],up:[0,0,1]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,-1,0],up:[0,0,1]},{boundaries:[[5,11,2,2]],dir:[1,1,1],up:[-1,-1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,-1,1],up:[-1,1,1]},{boundaries:[[5,5,2,2]],dir:[1,1,-1],up:[1,1,1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,-1,1],up:[1,1,1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,-1],up:[-1,-1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,1],up:[1,-1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,-1],up:[1,-1,1]},{boundaries:[[11,5,2,2]],dir:[-1,1,-1],up:[-1,1,1]}],l=(t.frontColor||t.color,t.backColor||t.color,t.leftColor||t.color,t.rightColor||t.color,t.topColor||t.color,t.bottomColor||t.color,[{label:"front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-1,-1],up:[0,1,-1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,-1,0],up:[1,1,0]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,-1,0],up:[-1,1,0]},{boundaries:[[7,11,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,1,0],up:[-1,1,0]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,1,1],up:[0,1,-1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,1,0],up:[1,1,0]},{boundaries:[[5,7,2,4]],dir:[1,0,-1],up:[0,1,0]},{boundaries:[[11,7,2,4]],dir:[-1,0,-1],up:[0,1,0]},{boundaries:[[17,7,2,4]],dir:[-1,0,1],up:[0,1,0]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,0,1],up:[0,1,0]},{boundaries:[[5,11,2,2]],dir:[1,1,-1],up:[-1,1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,1,1],up:[-1,1,-1]},{boundaries:[[5,5,2,2]],dir:[1,-1,-1],up:[1,1,-1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,1,1],up:[1,1,-1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,1],up:[-1,1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,-1],up:[1,1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,1],up:[1,1,1]},{boundaries:[[11,5,2,2]],dir:[-1,-1,-1],up:[-1,1,-1]}]);for(let e=0,t=n.length;e=r[0]*o&&t<=(r[0]+r[2])*o&&i>=r[1]*o&&i<=(r[1]+r[3])*o)return s}}return-1},this.setAreaHighlighted=function(e,t){var i=h[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,d()},this.getAreaDir=function(e){var t=h[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=h[e];if(!t)throw"Unknown area: "+e;return t.up},this.getImage=function(){return this._textureCanvas},this.destroy=function(){this._textureCanvas&&(this._textureCanvas.parentNode.removeChild(this._textureCanvas),this._textureCanvas=null)},this.clear()}class NavCubePlugin extends Plugin{constructor(e,t={}){super("NavCube",e,t),e.navCube=this;try{this._navCubeScene=new Scene({canvasId:t.canvasId,canvasElement:t.canvasElement,transparent:!0}),this._navCubeCanvas=this._navCubeScene.canvas.canvas,this._navCubeScene.input.keyboardEnabled=!1}catch(e){return void this.error(e)}const i=this._navCubeScene;i.clearLights(),new DirLight(i,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new DirLight(i,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new DirLight(i,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._navCubeCamera=i.camera,this._navCubeCamera.ortho.scale=7,this._navCubeCamera.ortho.near=.1,this._navCubeCamera.ortho.far=2e3,this._zUp=Boolean(e.camera.zUp);var s,r,o,a,n=this;this._synchCamera=(s=math.rotationMat4c(-90*math.DEGTORAD,1,0,0),r=math.vec3(),o=math.vec3(),a=math.vec3(),function(){var t=e.camera.eye,i=e.camera.look,l=e.camera.up;r=math.mulVec3Scalar(math.normalizeVec3(math.subVec3(t,i,r)),5),n._zUp?(math.transformVec3(s,r,o),math.transformVec3(s,l,a),n._navCubeCamera.look=[0,0,0],n._navCubeCamera.eye=math.transformVec3(s,r,o),n._navCubeCamera.up=math.transformPoint3(s,l,a)):(n._navCubeCamera.look=[0,0,0],n._navCubeCamera.eye=r,n._navCubeCamera.up=l)}),this._cubeTextureCanvas=new CubeTextureCanvas(e,t),this._cubeSampler=new Texture(i,{image:this._cubeTextureCanvas.getImage(),flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge"}),this._cubeMesh=new Mesh(i,{geometry:new ReadableGeometry(i,{primitive:"triangles",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],positions:[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],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],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]}),material:new PhongMaterial(i,{diffuse:[.4,.4,.4],specular:[.4,.4,.4],emissive:[.6,.6,.6],diffuseMap:this._cubeSampler,emissiveMap:this._cubeSampler}),visible:!0,edges:!0}),this._shadow=new Mesh(i,{geometry:new ReadableGeometry(i,buildCylinderGeometry({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new PhongMaterial(i,{diffuse:[0,0,0],specular:[0,0,0],emissive:[0,0,0],alpha:.5}),position:[0,-1.5,0],visible:!0,pickable:!1,backfaces:!1}),this._onCameraMatrix=e.camera.on("matrix",this._synchCamera),this._onCameraWorldAxis=e.camera.on("worldAxis",()=>{e.camera.zUp?(this._zUp=!0,this._cubeTextureCanvas.setZUp(),this._repaint(),this._synchCamera()):e.camera.yUp&&(this._zUp=!1,this._cubeTextureCanvas.setYUp(),this._repaint(),this._synchCamera())}),this._onCameraFOV=e.camera.perspective.on("fov",e=>{this._synchProjection&&(this._navCubeCamera.perspective.fov=e)}),this._onCameraProjection=e.camera.on("projection",e=>{this._synchProjection&&(this._navCubeCamera.projection=e)});var l=-1;function h(e){var t=[0,0];if(e){for(var i=e.target,s=0,r=0;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}var c,d,u=null,p=null,m=!1,_=!1,f=.5;n._navCubeCanvas.addEventListener("mouseenter",n._onMouseEnter=function(e){_=!0}),n._navCubeCanvas.addEventListener("mouseleave",n._onMouseLeave=function(e){_=!1}),n._navCubeCanvas.addEventListener("mousedown",n._onMouseDown=function(e){if(1===e.which){u=e.x,p=e.y,c=e.clientX,d=e.clientY;var t=h(e),s=i.pick({canvasPos:t});m=!!s}}),document.addEventListener("mouseup",n._onMouseUp=function(e){if(1===e.which&&(m=!1,null!==u)){var t=h(e),s=i.pick({canvasPos:t,pickSurface:!0});if(s&&s.uv){var r=n._cubeTextureCanvas.getArea(s.uv);if(r>=0&&(document.body.style.cursor="pointer",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),r>=0)){if(n._cubeTextureCanvas.setAreaHighlighted(r,!0),l=r,n._repaint(),e.xu+3||e.yp+3)return;var o=n._cubeTextureCanvas.getAreaDir(r);if(o){var a=n._cubeTextureCanvas.getAreaUp(r);v(o,a,function(){l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1);var e=i.pick({canvasPos:t,pickSurface:!0});if(e&&e.uv){var s=n._cubeTextureCanvas.getArea(e.uv);void 0!==s&&(document.body.style.cursor="pointer",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),s>=0&&(n._cubeTextureCanvas.setAreaHighlighted(s,!0),l=s,n._repaint()))}})}}}}}),document.addEventListener("mousemove",n._onMouseMove=function(t){if(l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),1!==t.buttons||m){if(m){var s=t.clientX,r=t.clientY;return document.body.style.cursor="move",void function(t,i){var s=(t-c)*-f,r=(i-d)*-f;e.camera.orbitYaw(s),e.camera.orbitPitch(-r),c=t,d=i}(s,r)}if(_){var o=h(t),a=i.pick({canvasPos:o,pickSurface:!0});if(a){if(a.uv){document.body.style.cursor="pointer";var u=n._cubeTextureCanvas.getArea(a.uv);if(u===l)return;l>=0&&n._cubeTextureCanvas.setAreaHighlighted(l,!1),u>=0&&(n._cubeTextureCanvas.setAreaHighlighted(u,!0),n._repaint(),l=u)}}else document.body.style.cursor="default",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1)}}});var g,v=(g=math.vec3(),function(t,i,s){var r=n._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,o=math.getAABB3Diag(r);math.getAABB3Center(r,g);var a=Math.abs(o/Math.tan(27.5));e.cameraControl.pivotPos=g,n._cameraFly?e.cameraFlight.flyTo({look:g,eye:[g[0]-a*t[0],g[1]-a*t[1],g[2]-a*t[2]],up:i||[0,1,0],orthoScale:1.3*o,fitFOV:n._cameraFitFOV,duration:n._cameraFlyDuration},s):e.cameraFlight.jumpTo({look:g,eye:[g[0]-a*t[0],g[1]-a*t[1],g[2]-a*t[2]],up:i||[0,1,0],orthoScale:1.3*o,fitFOV:n._cameraFitFOV},s)});this.setVisible(t.visible),this.setCameraFitFOV(t.cameraFitFOV),this.setCameraFly(t.cameraFly),this.setCameraFlyDuration(t.cameraFlyDuration),this.setFitVisible(t.fitVisible),this.setSynchProjection(t.synchProjection)}send(e,t){switch(e){case"language":this._cubeTextureCanvas.clear(),this._repaint()}}_repaint(){const e=this._cubeTextureCanvas.getImage();this._cubeMesh.material.diffuseMap.image=e,this._cubeMesh.material.emissiveMap.image=e}setVisible(e=!0){this._navCubeCanvas&&(this._cubeMesh.visible=e,this._shadow.visible=e,this._navCubeCanvas.style.visibility=e?"visible":"hidden")}getVisible(){return!!this._navCubeCanvas&&this._cubeMesh.visible}setFitVisible(e=!1){this._fitVisible=e}getFitVisible(){return this._fitVisible}setCameraFly(e=!0){this._cameraFly=e}getCameraFly(){return this._cameraFly}setCameraFitFOV(e=45){this._cameraFitFOV=e}getCameraFitFOV(){return this._cameraFitFOV}setCameraFlyDuration(e=.5){this._cameraFlyDuration=e}getCameraFlyDuration(){return this._cameraFlyDuration}setSynchProjection(e=!1){this._synchProjection=e}getSynchProjection(){return this._synchProjection}destroy(){this._navCubeCanvas&&(this.viewer.camera.off(this._onCameraMatrix),this.viewer.camera.off(this._onCameraWorldAxis),this.viewer.camera.perspective.off(this._onCameraFOV),this.viewer.camera.off(this._onCameraProjection),this._navCubeCanvas.removeEventListener("mouseenter",this._onMouseEnter),this._navCubeCanvas.removeEventListener("mouseleave",this._onMouseLeave),this._navCubeCanvas.removeEventListener("mousedown",this._onMouseDown),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),this._navCubeCanvas=null,this._cubeTextureCanvas.destroy(),this._cubeTextureCanvas=null,this._onMouseEnter=null,this._onMouseLeave=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null),this._navCubeScene.destroy(),this._navCubeScene=null,this._cubeMesh=null,this._shadow=null,super.destroy()}}class NavCubeMode extends Controller{constructor(e,t){if(super(e,t),!t.navCubeCanvasElement)throw"Missing config: navCubeCanvasElement";const i=t.navCubeCanvasElement;this._navCube=new NavCubePlugin(this.viewer,{canvasElement:i,fitVisible:!0,color:"#CFCFCF"}),this._navCube.setVisible(this._active),this.on("active",e=>{this._navCube.setVisible(e)})}destroy(){this._navCube.destroy(),super.destroy()}}class PerformanceMesh{constructor(e,t,i,s,r=null,o=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.pickId=this.model.scene._renderer.getPickID(this),this.aabb=math.AABB3(),this._layer=r,this._portionId=o,this._color=[i[0],i[1],i[2],s],this._colorize=[i[0],i[1],i[2],s],this._colorizing=!1,this.numTriangles=0,this.rtcCenter=null}_initFlags(e){this._layer.initFlags(this._portionId,e)}_setVisible(e){this._layer.setVisible(this._portionId,e)}_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,!1),this._colorizing=!0):(this._layer.setColor(this._portionId,this._color,!1),this._colorizing=!1)}_setOpacity(e){this._color[3]=e,this._colorize[3]=e;this._colorizing?this._layer.setColor(this._portionId,this._colorize,!0):this._layer.setColor(this._portionId,this._color,!0)}_setOffset(e){this._layer.setOffset(this._portionId,e)}_setHighlighted(e){this._layer.setHighlighted(this._portionId,e)}_setXRayed(e){this._layer.setXRayed(this._portionId,e)}_setSelected(e){this._layer.setSelected(this._portionId,e)}_setEdges(e){this._layer.setEdges(this._portionId,e)}_setClippable(e){this._layer.setClippable(this._portionId,e)}_setCollidable(e){this._layer.setCollidable(this._portionId,e)}_setPickable(e){this._layer.setPickable(this._portionId,e)}_setCulled(e){this._layer.setCulled(this._portionId,e)}canPickTriangle(){return!1}drawPickTriangles(e){}pickTriangleSurface(e){}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const RENDER_FLAGS={VISIBLE:1,CULLED:4,PICKABLE:8,CLIPPABLE:16,COLLIDABLE:32,CAST_SHADOW:64,RECEIVE_SHADOW:128,XRAYED:256,HIGHLIGHTED:512,SELECTED:1024,EDGES:2048,BACKFACES:4096},tempFloatRGB=new Float32Array([0,0,0]),tempIntRGB=new Uint16Array([0,0,0]);class PerformanceNode{constructor(e,t,i,s,r,o){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=s,this._numTriangles=0;for(var a=0,n=this.meshes.length;a1&&(e=1),e=Math.floor(255*e),this.meshes[0]._colorize[3]/255===e)return}else e=255;for(let t=0,i=this.meshes.length;t0?this.meshes[0]._colorize[3]/255: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.meshes.length;e{batchingLayerScratchMemory._clear()}),batchingLayerScratchMemory}const RENDER_PASSES={NORMAL_OPAQUE:0,NORMAL_TRANSPARENT:1,NORMAL_EDGES:2,HIGHLIGHTED:3,HIGHLIGHTED_EDGES:4,XRAYED:5,XRAYED_EDGES:6,SELECTED:7,SELECTED_EDGES:8},BatchingDrawShaderSource=function(e,t){this.vertex=buildVertex$6(e),this.fragment=buildFragment$6(e,t)};function buildVertex$6(e){const t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0;let r,o,a;const n=[];for(n.push("// Batched geometry drawing vertex shader"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),n.push("attribute vec3 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("attribute vec3 offset;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),n.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vColor;"),n.push("void main(void) {"),n.push("bool visible = (float(flags.x) > 0.0);"),n.push("bool xrayed = (float(flags.y) > 0.0);"),n.push("bool highlighted = (float(flags.z) > 0.0);"),n.push("bool selected = (float(flags.w) > 0.0);"),n.push("bool culled = (float(flags2.w) > 0.0);"),n.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),n.push(`if (\n culled || !visible || \n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),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;"),r=0,o=i.lights.length;r0,a=[];if(a.push("// Batched geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),o)for(a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),s=0,r=i.sectionPlanes.length;s 0.0);"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,r=i.sectionPlanes.length;s 0.0) { discard; }"),a.push("}")}return t?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push(" gl_FragColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" gl_FragColor = vColor;"),a.push("}"),a}const tempVec4$1=math.vec4(),tempVec3a$9=math.vec3();class BatchingDrawRenderer{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._shaderSource=new BatchingDrawShaderSource(this._scene,this._withSAO),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=t.model,o=s.canvas.gl,a=t._state,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e),l=!0),o.uniformMatrix4fv(this._uViewMatrix,!1,n?createRTCViewMat(r.viewMatrix,n):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=r.renderFlags;for(let t=0;t0),s=[];return s.push("// Batched fill vertex shader"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec4 color;"),i&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("bool visible = (float(flags.x) > 0.0);"),s.push("bool xrayed = (float(flags.y) > 0.0);"),s.push("bool highlighted = (float(flags.z) > 0.0);"),s.push("bool selected = (float(flags.w) > 0.0);"),s.push("bool clippable = (float(flags2.x) > 0.0);"),s.push("bool culled = (float(flags2.w) > 0.0);"),s.push("bool transparent = (color.a < 1.0);"),s.push(`if (\n culled || !visible ||\n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),i&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2;")),s.push("gl_Position = projMatrix * viewPosition;"),s.push("}"),s.push("}"),s}function buildFragment$7(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Batched fill 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i 0.0) { discard; }"),o.push("}")}return o.push("gl_FragColor = color;"),o.push("}"),o}const defaultColor=new Float32Array([1,1,1]),tempVec3a$a=math.vec3();class BatchingFillRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingFillShaderSource(this._scene),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.canvas.gl,a=t._state,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0);const h=n?createRTCViewMat(s.viewMatrix,n):s.viewMatrix;if(o.uniformMatrix4fv(this._uViewMatrix,!1,h),o.uniformMatrix4fv(this._uModelMatrix,!1,s.worldMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("uniform vec4 color;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool highlighted = (float(flags.z) > 0.0);"),i.push("bool selected = (float(flags.w) > 0.0);"),i.push("bool edges = (float(flags2.y) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("bool transparent = (color.a < 1.0);"),i.push(`if (\n culled || !visible ||\n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (!edges || transparent || xrayed)) ||\n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!edges || !transparent || xrayed || highlighted || selected)) ||\n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) ||\n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$8(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Batched geometry 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i 0.0) { discard; }"),o.push("}")}return o.push("gl_FragColor = color;"),o.push("}"),o}const tempVec3a$b=math.vec3();class BatchingEdgesRenderer{constructor(e){this._scene=e,this._shaderSource=new BatchingEdgesShaderSource(this._scene),this._allocate(),this._hash=this._getHash()}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.canvas.gl,a=t._state,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0);const h=n?createRTCViewMat(s.viewMatrix,n):s.viewMatrix;if(o.uniformMatrix4fv(this._uViewMatrix,!1,h),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry picking vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 pickColor;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vPickColor;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool pickable = (float(flags2.z) > 0.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || (!pickInvisible && !visible) || !pickable) {"),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.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(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$9(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = vPickColor; "),s.push("}"),s}const tempVec3a$c=math.vec3();class BatchingPickMeshRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickMeshShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=t._state.rtcCenter;this._program||this._allocate(t);let n=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e),n=!0);const l=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,h=a?createRTCViewMat(l,a):l;if(r.uniformMatrix4fv(this._uViewMatrix,!1,h),a?e.lastRTCCenter&&math.compareVec3(a,e.lastRTCCenter)||(e.lastRTCCenter=a,n=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,n=!0),n){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool pickable = (float(flags2.z) > 0.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || (!pickInvisible && !visible) || !pickable) {"),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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$a(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),s.push("uniform float zNear;"),s.push("uniform float zFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" float zNormalizedDepth = abs((zNear + vViewPosition.z) / (zFar - zNear));"),s.push(" gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}const tempVec3a$d=math.vec3();class BatchingPickDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=s.camera.project._state,n=t._state.rtcCenter;this._program||this._allocate();let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniform1i(this._uPickInvisible,e.pickInvisible);const h=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,c=n?createRTCViewMat(h,n):h;if(r.uniformMatrix4fv(this._uViewMatrix,!1,c),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.uniform1f(this._uZNear,a.near),r.uniform1f(this._uZFar,a.far),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry normals vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vWorldNormal;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool pickable = (float(flags2.z) > 0.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || (!pickInvisible && !visible) || !pickable) {"),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.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(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$b(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}const tempVec3a$e=math.vec3();class BatchingPickNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=t._state.rtcCenter;this._program||this._allocate(t);let n=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),n=!0),r.uniform1i(this._uPickInvisible,e.pickInvisible);const l=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,h=a?createRTCViewMat(l,a):l;if(r.uniformMatrix4fv(this._uViewMatrix,!1,h),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),a?e.lastRTCCenter&&math.compareVec3(a,e.lastRTCCenter)||(e.lastRTCCenter=a,n=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,n=!0),n){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched occlusion vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (culled || !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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$c(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched 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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}const tempVec3a$f=math.vec3();class BatchingOcclusionRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingOcclusionShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=s.camera,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0);const h=n?createRTCViewMat(i.viewMatrix,n):i.viewMatrix;if(r.uniformMatrix4fv(this._uViewMatrix,!1,h),r.uniformMatrix4fv(this._uProjMatrix,!1,a._project._state.matrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool xrayed = (float(flags.y) > 0.0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || !visible || transparent || xrayed) {"),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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$d(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = packDepthToRGBA( gl_FragCoord.z); "),s.push("}"),s}const tempVec3a$g=math.vec3();class BatchingDepthRenderer{constructor(e){this._scene=e,this._shaderSource=new BatchingDepthShaderSource(this._scene),this._allocate(this._scene),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let n=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),n=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,a?createRTCViewMat(i.viewMatrix,a):i.viewMatrix),a?e.lastRTCCenter&&math.compareVec3(a,e.lastRTCCenter)||(e.lastRTCCenter=a,n=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,n=!0),n){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry normals vertex shader"),i.push("attribute vec3 position;"),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 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.0);"),i.push(" bool xrayed = (float(flags.y) > 0.0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || !visible || transparent || xrayed) {"),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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = 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(" gl_Position = projMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$e(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}const tempVec3a$h=math.vec3(),tempMat4a=math.mat4();class BatchingNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let n=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t),n=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,a?createRTCViewMat(i.viewMatrix,a):i.viewMatrix),r.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),a?e.lastRTCCenter&&math.compareVec3(a,e.lastRTCCenter)||(e.lastRTCCenter=a,n=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,n=!0),n){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Batched geometry shadow vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push(" bool visible = (float(flags.x) > 0.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.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}function buildFragment$f(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}const tempVec3a$i=math.vec3();class BatchingShadowRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingShadowShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=this._scene,s=i.canvas.gl,r=t._state;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aColor&&this._aColor.bindArrayBuffer(r.colorsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(r.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(r.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(r.offsetsBuf),r.indicesBuf.bind();const o=i._sectionPlanesState.sectionPlanes.length;if(o>0){const e=i._sectionPlanesState.sectionPlanes,r=t.layerIndex*o,a=model.renderFlags,n=t._state.rtcCenter;for(let t=0;t{i._compile()}),e.on("destroyed",()=>{delete sceneBatchingRenderers[t],i._destroy()})),i}const bigIndicesSupported$1=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,MAX_VERTS=bigIndicesSupported$1?5e6:65530,MAX_INDICES=3*MAX_VERTS;class BatchingBuffer{constructor(){this.maxVerts=MAX_VERTS,this.maxIndices=MAX_INDICES,this.positions=[],this.colors=[],this.normals=[],this.pickColors=[],this.flags=[],this.flags2=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const tempMat4=math.mat4(),tempMat4b=math.mat4(),tempVec4a=math.vec4([0,0,0,1]),tempVec4b=math.vec4([0,0,0,1]),tempVec4c=math.vec4([0,0,0,1]),tempOBB3=math.OBB3();class BatchingLayer{constructor(e,t){this.layerIndex=t.layerIndex,this._batchingRenderers=getBatchingRenderers(e.scene),this.model=e,this._buffer=new BatchingBuffer,this._scratchMemory=t.scratchMemory;var i,s=t.primitive||"triangles";const r=e.scene.canvas.gl;switch(s){case"points":i=r.POINTS;break;case"lines":i=r.LINES;break;case"line-loop":i=r.LINE_LOOP;break;case"line-strip":i=r.LINE_STRIP;break;case"triangles":i=r.TRIANGLES;break;case"triangle-strip":i=r.TRIANGLE_STRIP;break;case"triangle-fan":i=r.TRIANGLE_FAN;break;default:e.error(`Unsupported value for 'primitive': '${s}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),i=r.TRIANGLES,s="triangles"}this._state=new RenderState({primitiveName:s,primitive:i,positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,flagsBuf:null,flags2Buf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:math.mat4(),rtcCenter: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=math.collapseAABB3(),this._portions=[],this._finalized=!1,this._positionsDecodeMatrix=t.positionsDecodeMatrix,this._preCompressed=!!this._positionsDecodeMatrix,t.rtcCenter&&(this._state.rtcCenter=math.vec3(t.rtcCenter)),this.aabb=math.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)if(this._preCompressed){e.positionsDecodeMatrix=this._positionsDecodeMatrix;const s=new Uint16Array(i.positions);e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=new Float32Array(i.positions),r=new Uint16Array(s.length);quantizePositions(s,i.positions.length,this._modelAABB,r,e.positionsDecodeMatrix),e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}if(i.normals.length>0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new ArrayBuf(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 ArrayBuf(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.flags.length>0){const s=new Uint8Array(i.flags),r=new Uint8Array(i.flags2);let o=!0;e.flagsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,i.flags.length,4,t.DYNAMIC_DRAW,o),e.flags2Buf=new ArrayBuf(t,t.ARRAY_BUFFER,r,i.flags.length,4,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}const s=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint;if(i.indices.length>0){const r=s?new Uint32Array(i.indices):new Uint16Array(i.indices);e.indicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,r,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const r=s?new Uint32Array(i.edgeIndices):new Uint16Array(i.edgeIndices);e.edgeIndicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,r,i.edgeIndices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t){t&RENDER_FLAGS.VISIBLE&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&RENDER_FLAGS.HIGHLIGHTED&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&RENDER_FLAGS.XRAYED&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&RENDER_FLAGS.SELECTED&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&RENDER_FLAGS.CLIPPABLE&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&RENDER_FLAGS.EDGES&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&RENDER_FLAGS.PICKABLE&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&RENDER_FLAGS.CULLED&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),this._setFlags(e,t),this._setFlags2(e,t)}setVisible(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.VISIBLE?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t)}setHighlighted(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.HIGHLIGHTED?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t)}setXRayed(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.XRAYED?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t)}setSelected(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.SELECTED?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t)}setEdges(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.EDGES?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags2(e,t)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.CLIPPABLE?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCulled(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.CULLED?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.PICKABLE?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t)}setColor(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=2*e,r=4*this._portions[s],o=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(o),n=t[0],l=t[1],h=t[2],c=t[3];for(var d=0;dh&&(n=o,h=l),(l=dot$1(u,a=octDecodeVec2$1(o=octEncodeVec3$1(u,"floor","ceil"))))>h&&(n=o,h=l),(l=dot$1(u,a=octDecodeVec2$1(o=octEncodeVec3$1(u,"ceil","ceil"))))>h&&(n=o,h=l),s[r+c+0]=n[0],s[r+c+1]=n[1],s[r+c+2]=0;return r+=i}function octEncodeVec3$1(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 octDecodeVec2$1(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 dot$1(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}const InstancingDrawShaderSource=function(e,t){this.vertex=buildVertex$g(e),this.fragment=buildFragment$g(e,t)};function buildVertex$g(e){const t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0;let r,o,a;const n=[];for(n.push("// Instancing geometry drawing vertex shader"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),n.push("attribute vec2 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),n.push("attribute vec3 offset;"),n.push("attribute vec4 modelMatrixCol0;"),n.push("attribute vec4 modelMatrixCol1;"),n.push("attribute vec4 modelMatrixCol2;"),n.push("attribute vec4 modelNormalMatrixCol0;"),n.push("attribute vec4 modelNormalMatrixCol1;"),n.push("attribute vec4 modelNormalMatrixCol2;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),n.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vColor;"),n.push("void main(void) {"),n.push("bool visible = (float(flags.x) > 0.0);"),n.push("bool xrayed = (float(flags.y) > 0.0);"),n.push("bool highlighted = (float(flags.z) > 0.0);"),n.push("bool selected = (float(flags.w) > 0.0);"),n.push("bool culled = (float(flags2.w) > 0.0);"),n.push("bool transparent = (float(color.a) < 255.0);"),n.push(`if \n (culled || !visible || \n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec4 worldNormal = vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),n.push("vec3 viewNormal = normalize(vec4(worldNormal * viewNormalMatrix).xyz);"),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;"),r=0,o=i.lights.length;r0,a=[];if(a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),o)for(a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),s=0,r=i.sectionPlanes.length;s 0.0);"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,r=i.sectionPlanes.length;s 0.0) { discard; }"),a.push("}")}return t?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push(" gl_FragColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" gl_FragColor = vColor;"),a.push("}"),a}const tempVec4$2=math.vec4(),tempVec3a$j=math.vec3(),tempMat4a$1=math.mat4(),tempMat4b$1=math.mat4();class InstancingDrawRenderer{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._shaderSource=new InstancingDrawShaderSource(this._scene,this._withSAO),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=t.model,r=s.scene,o=r.canvas.gl,a=t._state,n=this._instanceExt,l=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let h=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e),h=!0),o.uniformMatrix4fv(this._uViewMatrix,!1,l?createRTCViewMat(s.viewMatrix,l):s.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,s.viewNormalMatrix),l?e.lastRTCCenter&&math.compareVec3(l,e.lastRTCCenter)||(e.lastRTCCenter=l,h=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,h=!0),h){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,n=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing fill vertex shader"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),i.push("uniform vec4 color;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool highlighted = (float(flags.z) > 0.0);"),i.push("bool selected = (float(flags.w) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("bool transparent = (color.a < 1.0);"),i.push(`if (\n culled || !visible ||\n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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);"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$h(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e 0.0) { discard; }"),s.push("}")}return s.push("gl_FragColor = color;"),s.push("}"),s}const tempVec3a$k=math.vec3();class InstancingFillRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingFillShaderSource(this._scene),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.canvas.gl,a=t._state,n=this._instanceExt,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t.model.scene),this.errors))return;let h=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),h=!0),o.uniformMatrix4fv(this._uViewMatrix,!1,l?createRTCViewMat(s.viewMatrix,l):s.viewMatrix),l?e.lastRTCCenter&&math.compareVec3(l,e.lastRTCCenter)||(e.lastRTCCenter=l,h=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,h=!0),h){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,n=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing edges vertex shader"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("uniform vec4 color;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool highlighted = (float(flags.z) > 0.0);"),i.push("bool selected = (float(flags.w) > 0.0);"),i.push("bool edges = (float(flags2.y) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("bool transparent = (color.a < 1.0);"),i.push(`if (\n culled || !visible || \n (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (!edges || transparent || xrayed)) ||\n (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!edges || !transparent || xrayed || highlighted || selected)) ||\n (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) ||\n (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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);"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$i(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0;let s,r;const o=[];if(o.push("// Instancing edges 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"),o.push("uniform vec4 color;"),i)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),s=0,r=t.sectionPlanes.length;s 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,r=t.sectionPlanes.length;s 0.0) { discard; }"),o.push("}")}return o.push("gl_FragColor = color;"),o.push("}"),o}const tempVec3a$l=math.vec3();class InstancingEdgesRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingEdgesShaderSource(this._scene),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.canvas.gl,a=t._state,n=this._instanceExt,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let h,c=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),c=!0),o.uniformMatrix4fv(this._uViewMatrix,!1,l?createRTCViewMat(s.viewMatrix,l):s.viewMatrix),l?e.lastRTCCenter&&math.compareVec3(l,e.lastRTCCenter)||(e.lastRTCCenter=l,c=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,c=!0),c){const e=r._sectionPlanesState.sectionPlanes.length;if(e>0){const i=r._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,n=s.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry picking vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 pickColor;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vPickColor;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool pickable = (float(flags2.z) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("if ( culled || (!pickInvisible && !visible) || !pickable) {"),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);"),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(" vFlags2 = flags2;")),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$j(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push("}")}return s.push("gl_FragColor = vPickColor; "),s.push("}"),s}const tempVec3a$m=math.vec3();class InstancingPickMeshRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickMeshShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e),l=!0);const h=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,c=n?createRTCViewMat(h,n):h;if(r.uniformMatrix4fv(this._uViewMatrix,!1,c),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(o.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(o.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(o.modelMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPickColor.bindArrayBuffer(o.pickColorsBuf),a.vertexAttribDivisorANGLE(this._aPickColor.location,1),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aFlags.bindArrayBuffer(o.flagsBuf),a.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(o.flags2Buf),a.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(o.offsetsBuf),a.vertexAttribDivisorANGLE(this._aOffset.location,1)),o.indicesBuf.bind(),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool pickable = (float(flags2.z) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("if (culled || (!pickInvisible && !visible) || !pickable) {"),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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$k(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),s.push("uniform float zNear;"),s.push("uniform float zFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" float zNormalizedDepth = abs((zNear + vViewPosition.z) / (zFar - zNear));"),s.push(" gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}const tempVec3a$n=math.vec3();class InstancingPickDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0);const h=s.camera.project._state;r.uniform1i(this._uPickInvisible,e.pickInvisible);const c=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,d=n?createRTCViewMat(c,n):c;if(r.uniformMatrix4fv(this._uViewMatrix,!1,d),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.uniform1f(this._uZNear,h.near),r.uniform1f(this._uZFar,h.far),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry normals vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec2 normal;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("attribute vec4 modelNormalMatrixCol0;"),i.push("attribute vec4 modelNormalMatrixCol1;"),i.push("attribute vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool pickable = (float(flags2.z) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push(" if (culled || (!pickInvisible && !visible) || !pickable) {"),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);"),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(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$l(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}const tempVec3a$o=math.vec3();class InstancingPickNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniform1i(this._uPickInvisible,e.pickInvisible);const h=e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix,c=n?createRTCViewMat(h,n):h;if(r.uniformMatrix4fv(this._uViewMatrix,!1,c),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing occlusion vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("if (culled || !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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$m(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}const tempVec3a$p=math.vec3();class InstancingOcclusionRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingOcclusionShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,n?createRTCViewMat(i.viewMatrix,n):i.viewMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry depth drawing vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("if ( culled || !visible || transparent || xrayed) {"),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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$n(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Instancing geometry depth 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i 0.0) { discard; }"),o.push("}")}return o.push(" gl_FragColor = packDepthToRGBA( gl_FragCoord.z); "),o.push("}"),o}const tempVec3a$q=math.vec3();class InstancingDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;let l=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,n?createRTCViewMat(i.viewMatrix,n):i.viewMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry depth drawing vertex shader"),i.push("attribute vec3 position;"),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("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.0);"),i.push("bool xrayed = (float(flags.y) > 0.0);"),i.push("bool culled = (float(flags2.w) > 0.0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (culled || !visible || transparent || xrayed) {"),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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = 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(" gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$o(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}const tempVec3a$r=math.vec3(),tempMat4a$2=math.mat4();class InstancingNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt,n=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;let l=!1;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(),l=!0),r.uniformMatrix4fv(this._uViewMatrix,!1,n?createRTCViewMat(i.viewMatrix,n):i.viewMatrix),r.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),n?e.lastRTCCenter&&math.compareVec3(n,e.lastRTCCenter)||(e.lastRTCCenter=n,l=!0):e.lastRTCCenter&&(e.lastRTCCenter=null,l=!0),l){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,a=t.layerIndex*e,l=i.renderFlags;for(let t=0;t0,i=[];return i.push("// Instancing geometry shadow drawing vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible = (float(flags.x) > 0.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);"),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$p(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Instancing geometry shadow 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i 0.0);"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i 0.0) { discard; }"),o.push("}")}return o.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),o.push("}"),o}const tempVec3a$s=math.vec3();class InstancingShadowRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._lastLightId=null,this._shaderSource=new InstancingShadowShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,t)),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(o.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(o.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(o.modelMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(o.offsetsBuf),a.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aColor.bindArrayBuffer(o.colorsBuf),a.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(o.flagsBuf),a.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(o.flags2Buf),a.vertexAttribDivisorANGLE(this._aFlags2.location,1));const n=s._sectionPlanesState.sectionPlanes.length;if(n>0){const e=s._sectionPlanesState.sectionPlanes,o=t.layerIndex*n,a=i.renderFlags,l=t._state.rtcCenter;for(let t=0;t{i._compile()}),e.on("destroyed",()=>{delete sceneInstancingRenderers[t],i._destroy()})),i}const bigIndicesSupported$2=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,MAX_VERTS$1=bigIndicesSupported$2?5e6:65530,quantizedPositions=new Uint16Array(3*MAX_VERTS$1),compressedNormals=new Int8Array(3*MAX_VERTS$1),tempUint8Vec4=new Uint8Array(4),tempVec3a$t=math.vec3(),tempVec4a$1=math.vec4([0,0,0,1]),tempVec4b$1=math.vec4([0,0,0,1]),tempVec4c$1=math.vec4([0,0,0,1]);class InstancingLayer{constructor(e,t){this.layerIndex=t.layerIndex,this._instancingRenderers=getInstancingRenderers(e.scene),this.model=e,this._aabb=math.collapseAABB3();let i,s=t.primitive||"triangles";const r=e.scene.canvas.gl;switch(s){case"points":i=r.POINTS;break;case"lines":i=r.LINES;break;case"line-loop":i=r.LINE_LOOP;break;case"line-strip":i=r.LINE_STRIP;break;case"triangles":i=r.TRIANGLES;break;case"triangle-strip":i=r.TRIANGLE_STRIP;break;case"triangle-fan":i=r.TRIANGLE_FAN;break;default:e.error(`Unsupported value for 'primitive': '${s}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),i=r.TRIANGLES,s="triangles"}const o={primitiveName:s,primitive:i,positionsDecodeMatrix:math.mat4(),numInstances:0,obb:math.OBB3(),rtcCenter:null},a=!!t.positionsDecodeMatrix;if(t.positions)if(a){let e=!1;o.positionsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,t.positions,t.positions.length,3,r.STATIC_DRAW,e),o.positionsDecodeMatrix.set(t.positionsDecodeMatrix);let i=math.collapseAABB3();math.expandAABB3Points3(i,t.positions),geometryCompressionUtils.decompressAABB(i,o.positionsDecodeMatrix),math.AABB3ToOBB3(i,o.obb)}else{let e=t.positions.length,i=math.collapseAABB3();math.expandAABB3Points3(i,t.positions),math.AABB3ToOBB3(i,o.obb),quantizePositions$1(t.positions,e,i,quantizedPositions,o.positionsDecodeMatrix);let s=!1;o.positionsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,quantizedPositions,e,3,r.STATIC_DRAW,s)}if(t.normals)if(a){const e=!0;o.normalsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,t.normals,t.normals.length,3,r.STATIC_DRAW,e)}else{const e=octEncodeNormals(t.normals,t.normals.length,compressedNormals,0),i=!0;o.normalsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,compressedNormals,e,3,r.STATIC_DRAW,i)}t.indices&&(o.indicesBuf=new ArrayBuf(r,r.ELEMENT_ARRAY_BUFFER,bigIndicesSupported$2?new Uint32Array(t.indices):new Uint16Array(t.indices),t.indices.length,1,r.STATIC_DRAW));let n=t.edgeIndices;n||(n=buildEdgeIndices(t.positions,t.indices,null,t.edgeThreshold||10)),o.edgeIndicesBuf=new ArrayBuf(r,r.ELEMENT_ARRAY_BUFFER,bigIndicesSupported$2?new Uint32Array(n):new Uint16Array(n),n.length,1,r.STATIC_DRAW),this._state=new RenderState(o),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=t.indices?t.indices.length/3:0,this._flags=[],this._flags2=[],this._colors=[],this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],t.rtcCenter&&(this._state.rtcCenter=math.vec3(t.rtcCenter)),this._finalized=!1,this.aabb=math.collapseAABB3()}createPortion(e,t,i,s,r,o,a){if(this._finalized)throw"Already finalized";const n=e&RENDER_FLAGS.VISIBLE?255:0,l=e&RENDER_FLAGS.XRAYED?255:0,h=e&RENDER_FLAGS.HIGHLIGHTED?255:0,c=e&RENDER_FLAGS.HIGHLIGHTED?255:0,d=e&RENDER_FLAGS.CLIPPABLE?255:0,u=e&RENDER_FLAGS.EDGES?255:0,p=e&RENDER_FLAGS.PICKABLE?255:0,m=e&RENDER_FLAGS.CULLED?255:0;this._flags.push(n),this._flags.push(l),this._flags.push(h),this._flags.push(c),this._flags2.push(d),this._flags2.push(u),this._flags2.push(p),this._flags2.push(m),n&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),l&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),h&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),c&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),d&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),u&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),p&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),m&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++);const _=t[0],f=t[1],g=t[2];t[3];i<255&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._colors.push(_),this._colors.push(f),this._colors.push(g),this._colors.push(i),this._offsets.push(0),this._offsets.push(0),this._offsets.push(0),this._modelMatrixCol0.push(s[0]),this._modelMatrixCol0.push(s[4]),this._modelMatrixCol0.push(s[8]),this._modelMatrixCol0.push(s[12]),this._modelMatrixCol1.push(s[1]),this._modelMatrixCol1.push(s[5]),this._modelMatrixCol1.push(s[9]),this._modelMatrixCol1.push(s[13]),this._modelMatrixCol2.push(s[2]),this._modelMatrixCol2.push(s[6]),this._modelMatrixCol2.push(s[10]),this._modelMatrixCol2.push(s[14]);let v=math.transposeMat4(s,math.mat4()),b=math.inverseMat4(v);this._modelNormalMatrixCol0.push(b[0]),this._modelNormalMatrixCol0.push(b[4]),this._modelNormalMatrixCol0.push(b[8]),this._modelNormalMatrixCol0.push(b[12]),this._modelNormalMatrixCol1.push(b[1]),this._modelNormalMatrixCol1.push(b[5]),this._modelNormalMatrixCol1.push(b[9]),this._modelNormalMatrixCol1.push(b[13]),this._modelNormalMatrixCol2.push(b[2]),this._modelNormalMatrixCol2.push(b[6]),this._modelNormalMatrixCol2.push(b[10]),this._modelNormalMatrixCol2.push(b[14]),this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]),math.collapseAABB3(o);const y=this._state.obb,M=y.length;for(let e=0;e0){const t=!1;this._state.colorsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(this._flags.length>0){const t=!0;this._state.flagsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._flags),this._flags.length,4,e.DYNAMIC_DRAW,t),this._state.flags2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._flags2),this._flags2.length,4,e.DYNAMIC_DRAW,t),this._flags=[],this._flags2=[]}if(this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._state.modelNormalMatrixCol0Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelNormalMatrixCol1Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelNormalMatrixCol2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;this._state.pickColorsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._finalized=!0}initFlags(e,t){t&RENDER_FLAGS.VISIBLE&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&RENDER_FLAGS.HIGHLIGHTED&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&RENDER_FLAGS.XRAYED&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&RENDER_FLAGS.SELECTED&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&RENDER_FLAGS.CLIPPABLE&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&RENDER_FLAGS.EDGES&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&RENDER_FLAGS.PICKABLE&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&RENDER_FLAGS.CULLED&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),this._setFlags(e,t),this._setFlags2(e,t)}setVisible(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.VISIBLE?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t)}setHighlighted(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.HIGHLIGHTED?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t)}setXRayed(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.XRAYED?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t)}setSelected(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.SELECTED?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t)}setEdges(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.EDGES?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags2(e,t)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.CLIPPABLE?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.PICKABLE?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t)}setCulled(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.CULLED?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags2(e,t)}setColor(e,t,i=!1){if(!this._finalized)throw"Not finalized";if(tempUint8Vec4[0]=t[0],tempUint8Vec4[1]=t[1],tempUint8Vec4[2]=t[2],tempUint8Vec4[3]=t[3],i){t[3]<255?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--)}this._state.colorsBuf.setData(tempUint8Vec4,4*e,4)}_setFlags(e,t){if(!this._finalized)throw"Not finalized";const i=t&RENDER_FLAGS.VISIBLE?255:0,s=t&RENDER_FLAGS.XRAYED?255:0,r=t&RENDER_FLAGS.HIGHLIGHTED?255:0,o=t&RENDER_FLAGS.SELECTED?255:0;tempUint8Vec4[0]=i,tempUint8Vec4[1]=s,tempUint8Vec4[2]=r,tempUint8Vec4[3]=o,this._state.flagsBuf.setData(tempUint8Vec4,4*e,4)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";const i=t&RENDER_FLAGS.CLIPPABLE?255:0,s=t&RENDER_FLAGS.EDGES?255:0,r=t&RENDER_FLAGS.PICKABLE?255:0,o=t&RENDER_FLAGS.CULLED?255:0;tempUint8Vec4[0]=i,tempUint8Vec4[1]=s,tempUint8Vec4[2]=r,tempUint8Vec4[3]=o,this._state.flags2Buf.setData(tempUint8Vec4,4*e,4)}setOffset(e,t){if(!this._finalized)throw"Not finalized";tempVec3a$t[0]=t[0],tempVec3a$t[1]=t[1],tempVec3a$t[2]=t[2],this._state.offsetsBuf.setData(tempVec3a$t,3*e,3)}drawNormalFillOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(e.withSAO?this._instancingRenderers.drawRendererWithSAO&&this._instancingRenderers.drawRendererWithSAO.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE):this._instancingRenderers.drawRenderer&&this._instancingRenderers.drawRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE))}drawNormalEdgesOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE)}drawNormalFillTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.drawRenderer&&this._instancingRenderers.drawRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_TRANSPARENT)}drawNormalTransparentEdges(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_TRANSPARENT)}drawDepth(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(e,this)}drawNormals(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(e,this)}drawXRayedFillOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedEdgesOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedFillTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedEdgesTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawHighlightedFillOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedEdgesOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedFillTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedEdgesTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawSelectedFillOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedEdgesOpaque(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedFillTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedEdgesTransparent(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawPickMesh(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(e,this)}drawPickDepths(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(e,this)}drawPickNormals(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickNormalsRenderer&&this._instancingRenderers.pickNormalsRenderer.drawLayer(e,this)}drawOcclusion(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(e,this)}drawShadow(e){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(e,this)}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=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.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const quantizePositions$1=function(){const e=math.mat4(),t=math.mat4(),i=math.vec3();return function(s,r,o,a,n){const l=o[0],h=o[1],c=o[2],d=o[3],u=o[4],p=o[5],m=o[3]-l,_=o[4]-h,f=o[5]-c,g=d!==l?65535/(d-l):0,v=u!==h?65535/(u-h):0,b=p!==c?65535/(p-c):0;for(let e=0;el&&(a=r,l=n),(n=dot$2(e,h,o=octDecodeVec2$2(r=octEncodeVec3$2(e,h,"floor","ceil"))))>l&&(a=r,l=n),(n=dot$2(e,h,o=octDecodeVec2$2(r=octEncodeVec3$2(e,h,"ceil","ceil"))))>l&&(a=r,l=n),i[s+h+0]=a[0],i[s+h+1]=a[1],i[s+h+2]=0;return s+=t}function octEncodeVec3$2(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=r,t=o;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 octDecodeVec2$2(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 dot$2(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const instancedArraysSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.ANGLE_instanced_arrays,tempMat4$1=math.mat4(),defaultScale=math.vec3([1,1,1]),defaultPosition=math.vec3([0,0,0]),defaultRotation=math.vec3([0,0,0]),defaultQuaternion=math.identityQuaternion();class PerformanceModel extends Component{constructor(e,t={}){super(e,t),this._aabb=math.collapseAABB3(),this._aabbDirty=!1,this._layerList=[],this._nodeList=[],this._lastDecodeMatrix=null,this._instancingLayers={},this._currentBatchingLayer=null,this._batchingScratchMemory=getBatchingLayerScratchMemory(this),this._meshes={},this._nodes={},this.renderFlags=new RenderFlags,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._edgeThreshold=t.edgeThreshold||10,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,this._position=new Float32Array(t.position||[0,0,0]),this._rotation=new Float32Array(t.rotation||[0,0,0]),this._quaternion=new Float32Array(t.quaternion||[0,0,0,1]),t.rotation&&math.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=new Float32Array(t.scale||[1,1,1]),this._worldMatrix=math.mat4(),math.composeMat4(this._position,this._quaternion,this._scale,this._worldMatrix),this._worldNormalMatrix=math.mat4(),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=math.mat4(),this._viewNormalMatrix=math.mat4(),this._viewMatrixDirty=!0,this._worldMatrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",()=>{this._viewMatrixDirty=!0})}get isPerformanceModel(){return!0}get position(){return this._position}get rotation(){return this._rotation}get quaternion(){return this._quaternion}get scale(){return this._scale}get matrix(){return this._worldMatrix}get worldMatrix(){return this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrix}get viewMatrix(){return this._viewMatrix?(this._viewMatrixDirty&&(math.mulMat4(this.scene.camera.viewMatrix,this._worldMatrix,this._viewMatrix),math.inverseMat4(this._viewMatrix,this._viewNormalMatrix),math.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewMatrix):this.scene.camera.viewMatrix}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}get viewNormalMatrix(){return this._viewNormalMatrix?(this._viewMatrixDirty&&(math.mulMat4(this.scene.camera.viewMatrix,this._worldMatrix,this._viewMatrix),math.inverseMat4(this._viewMatrix,this._viewNormalMatrix),math.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}createGeometry(e){if(!instancedArraysSupported)return void this.error("WebGL instanced arrays not supported");const t=e.id;if(void 0===t||null===t)return void this.error("Config missing: id");if(this._instancingLayers[t])return void this.error("Geometry already created: "+t);const i=new InstancingLayer(this,utils.apply({layerIndex:0,edgeThreshold:this._edgeThreshold},e));this._instancingLayers[t]=i,this._layerList.push(i),this.numGeometries++,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0}createMesh(e){let t=e.id;if(void 0===t||null===t)return void this.error("Config missing: id");if(this._meshes[t])return void this.error("PerformanceModel already has a Mesh with this ID: "+t);const i=e.geometryId,s=void 0!==i;if(s){if(!instancedArraysSupported)return void this.error("WebGL instanced arrays not supported");if(!this._instancingLayers[i])return void this.error("Geometry not found: "+i+" - ensure that you create it first with createGeometry()")}let r,o;const a=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],n=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;n<255&&this.numTransparentLayerPortions++;const l=new PerformanceMesh(this,t,a,n),h=l.pickId,c=new Uint8Array([255&h,h>>8&255,h>>16&255,h>>24&255]),d=math.collapseAABB3();if(s){let t,s=this._worldMatrixNonIdentity?this._worldMatrix:null;if(e.matrix)t=e.matrix;else{const i=e.scale||defaultScale,s=e.position||defaultPosition,r=e.rotation||defaultRotation;math.eulerToQuaternion(r,"XYZ",defaultQuaternion),t=math.composeMat4(s,defaultQuaternion,i,tempMat4$1)}const h=this._instancingLayers[i];r=h,o=h.createPortion(0,a,n,t,s,d,c),math.expandAABB3(this._aabb,d);const u=Math.round(h.numIndices/3);this._numTriangles+=u,l.numTriangles=u,l.rtcCenter=h.rtcCenter}else{let t=e.primitive||"triangles";"points"!==t&&"lines"!==t&&"line-loop"!==t&&"line-strip"!==t&&"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t&&(this.error(`Unsupported value for 'primitive': '${t}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),t="triangles");let i=e.indices,s=e.edgeIndices,h=e.positions;if(!h)return this.error("Config missing: positions (no meshIds provided, so expecting geometry arrays instead)"),null;let u=e.normals;if(!u)return this.error("Config missing: normals (no meshIds provided, so expecting geometry arrays instead)"),null;if(!s&&!i)return this.error("Config missing: must have one or both of indices and edgeIndices (no meshIds provided, so expecting geometry arrays instead)"),null;let p,m=!1;e.rtcCenter&&(this._lastRTCCenter?math.compareVec3(this._lastRTCCenter,e.rtcCenter)||(m=!0,this._lastRTCCenter.set(e.rtcCenter)):(m=!0,this._lastRTCCenter=math.vec3(e.rtcCenter))),e.positionsDecodeMatrix&&(this._lastDecodeMatrix?math.compareMat4(this._lastDecodeMatrix,e.positionsDecodeMatrix)||(m=!0,this._lastDecodeMatrix.set(e.positionsDecodeMatrix)):(m=!0,this._lastDecodeMatrix=math.mat4(e.positionsDecodeMatrix))),m&&this._currentBatchingLayer&&(this._currentBatchingLayer.finalize(),this._currentBatchingLayer=null),this._currentBatchingLayer&&(this._currentBatchingLayer.canCreatePortion(h.length,i.length)||(this._currentBatchingLayer.finalize(),this._currentBatchingLayer=null)),this._currentBatchingLayer||(this._currentBatchingLayer=new BatchingLayer(this,{layerIndex:0,primitive:"triangles",scratchMemory:this._batchingScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,rtcCenter:e.rtcCenter}),this._layerList.push(this._currentBatchingLayer)),r=this._currentBatchingLayer,!s&&i&&(s=buildEdgeIndices(h,i,null,this._edgeThreshold));let _=this._worldMatrixNonIdentity?this._worldMatrix:null;if(!e.positionsDecodeMatrix)if(e.matrix)p=e.matrix;else{const t=e.scale||defaultScale,i=e.position||defaultPosition,s=e.rotation||defaultRotation;math.eulerToQuaternion(s,"XYZ",defaultQuaternion),p=math.composeMat4(i,defaultQuaternion,t,tempMat4$1)}o=this._currentBatchingLayer.createPortion(h,u,i,s,0,a,n,p,_,d,c),math.expandAABB3(this._aabb,d),this.numGeometries++;const f=Math.round(i.length/3);this._numTriangles+=f,l.numTriangles=f,l.rtcCenter=e.rtcCenter}l.parent=null,l._layer=r,l._portionId=o,l.aabb=d,this._meshes[t]=l}createEntity(e){let t=e.id;void 0===t?t=math.createUUID():this.scene.components[t]&&(this.error("Scene already has a Component with this ID: "+t+" - will assign random ID"),t=math.createUUID());const i=e.meshIds;if(void 0===i)return void this.error("Config missing: meshIds");let s,r,o,a,n=[];for(s=0,r=i.length;s0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._nodeList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._nodeList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._nodeList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._nodeList.length;t0}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._nodeList.length;t0}set colorize(e){this._colorize=e;for(let t=0,i=this._nodeList.length;t0&&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;t0)for(let o=0;o0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedFillTransparent=!0:e.xrayedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){const t=this.scene.edgeMaterial._state;t.edges&&(t.alpha<1?e.normalEdgesTransparent=!0:e.normalEdgesOpaque=!0)}if(this.numTransparentLayerPortions>0&&(e.normalFillTransparent=!0),this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedFillTransparent=!0:e.selectedFillOpaque=!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.highlightedFillTransparent=!0:e.highlightedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}drawNormalFillOpaque(e){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i{t(e)},function(e){i(e)})}getXKT(e,t,i){var s=()=>{};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),s=new Uint8Array(e);for(var a=0;a0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new n,this.strm.avail_out=0;var i=s.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==h)throw new Error(a[i]);if(t.header&&s.deflateSetHeader(this.strm,t.header),t.dictionary){var m;if(m="string"==typeof t.dictionary?o.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=s.deflateSetDictionary(this.strm,m))!==h)throw new Error(a[i]);this._dict_set=!0}}function m(e,t){var i=new p(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}p.prototype.push=function(e,t){var i,a,n=this.strm,c=this.options.chunkSize;if(this.ended)return!1;a=t===~~t?t:!0===t?4:0,"string"==typeof e?n.input=o.string2buf(e):"[object ArrayBuffer]"===l.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;do{if(0===n.avail_out&&(n.output=new r.Buf8(c),n.next_out=0,n.avail_out=c),1!==(i=s.deflate(n,a))&&i!==h)return this.onEnd(i),this.ended=!0,!1;0!==n.avail_out&&(0!==n.avail_in||4!==a&&2!==a)||("string"===this.options.to?this.onData(o.buf2binstring(r.shrinkBuf(n.output,n.next_out))):this.onData(r.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||0===n.avail_out)&&1!==i);return 4===a?(i=s.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===h):2!==a||(this.onEnd(h),n.avail_out=0,!0)},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===h&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=p,i.deflate=m,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,m(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,m(e,t)}},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(e,t,i){var s=e("./zlib/inflate"),r=e("./utils/common"),o=e("./utils/strings"),a=e("./zlib/constants"),n=e("./zlib/messages"),l=e("./zlib/zstream"),h=e("./zlib/gzheader"),c=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=r.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=s.inflateInit2(this.strm,t.windowBits);if(i!==a.Z_OK)throw new Error(n[i]);if(this.header=new h,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===c.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=s.inflateSetDictionary(this.strm,t.dictionary))!==a.Z_OK))throw new Error(n[i])}function u(e,t){var i=new d(t);if(i.push(e,!0),i.err)throw i.msg||n[i.err];return i.result}d.prototype.push=function(e,t){var i,n,l,h,d,u=this.strm,p=this.options.chunkSize,m=this.options.dictionary,_=!1;if(this.ended)return!1;n=t===~~t?t:!0===t?a.Z_FINISH:a.Z_NO_FLUSH,"string"==typeof e?u.input=o.binstring2buf(e):"[object ArrayBuffer]"===c.call(e)?u.input=new Uint8Array(e):u.input=e,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new r.Buf8(p),u.next_out=0,u.avail_out=p),(i=s.inflate(u,a.Z_NO_FLUSH))===a.Z_NEED_DICT&&m&&(i=s.inflateSetDictionary(this.strm,m)),i===a.Z_BUF_ERROR&&!0===_&&(i=a.Z_OK,_=!1),i!==a.Z_STREAM_END&&i!==a.Z_OK)return this.onEnd(i),this.ended=!0,!1;u.next_out&&(0!==u.avail_out&&i!==a.Z_STREAM_END&&(0!==u.avail_in||n!==a.Z_FINISH&&n!==a.Z_SYNC_FLUSH)||("string"===this.options.to?(l=o.utf8border(u.output,u.next_out),h=u.next_out-l,d=o.buf2string(u.output,l),u.next_out=h,u.avail_out=p-h,h&&r.arraySet(u.output,u.output,l,h,0),this.onData(d)):this.onData(r.shrinkBuf(u.output,u.next_out)))),0===u.avail_in&&0===u.avail_out&&(_=!0)}while((u.avail_in>0||0===u.avail_out)&&i!==a.Z_STREAM_END);return i===a.Z_STREAM_END&&(n=a.Z_FINISH),n===a.Z_FINISH?(i=s.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===a.Z_OK):n!==a.Z_SYNC_FLUSH||(this.onEnd(a.Z_OK),u.avail_out=0,!0)},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===a.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=d,i.inflate=u,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,u(e,t)},i.ungzip=u},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(e,t,i){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var s in i)r(i,s)&&(e[s]=i[s])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var o={arraySet:function(e,t,i,s,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+s),r);else for(var o=0;o=252?6:n>=248?5:n>=240?4:n>=224?3:n>=192?2:1;function l(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&r))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var i="",a=0;a>>6,t[a++]=128|63&i):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|63&i):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new s.Buf8(e.length),i=0,r=t.length;i4)h[s++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&i1?h[s++]=65533:r<65536?h[s++]=r:(r-=65536,h[s++]=55296|r>>10&1023,h[s++]=56320|1023&r)}return l(h,s)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0?t:0===i?t:i+a[e[i]]>t?i:t}},{"./common":3}],5:[function(e,t,i){t.exports=function(e,t,i,s){for(var r=65535&e|0,o=e>>>16&65535|0,a=0;0!==i;){i-=a=i>2e3?2e3:i;do{o=o+(r=r+t[s++]|0)|0}while(--a);r%=65521,o%=65521}return r|o<<16|0}},{}],6:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],7:[function(e,t,i){var s=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,r){var o=s,a=r+i;e^=-1;for(var n=r;n>>8^o[255&(e^t[n])];return-1^e}},{}],8:[function(e,t,i){var s,r=e("../utils/common"),o=e("./trees"),a=e("./adler32"),n=e("./crc32"),l=e("./messages"),h=0,c=1,d=3,u=4,p=5,m=0,_=1,f=-2,g=-3,v=-5,b=-1,y=1,M=2,w=3,P=4,x=0,E=2,A=8,C=9,R=15,S=8,L=286,D=30,T=19,k=2*L+1,B=15,I=3,F=258,N=F+I+1,V=32,O=42,j=69,U=73,G=91,z=103,H=113,$=666,W=1,X=2,Y=3,q=4,K=3;function Z(e,t){return e.msg=l[t],t}function Q(e){return(e<<1)-(e>4?9:0)}function J(e){for(var t=e.length;--t>=0;)e[t]=0}function ee(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(r.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function te(e,t){o._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ee(e.strm)}function ie(e,t){e.pending_buf[e.pending++]=t}function se(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function re(e,t){var i,s,r=e.max_chain_length,o=e.strstart,a=e.prev_length,n=e.nice_match,l=e.strstart>e.w_size-N?e.strstart-(e.w_size-N):0,h=e.window,c=e.w_mask,d=e.prev,u=e.strstart+F,p=h[o+a-1],m=h[o+a];e.prev_length>=e.good_match&&(r>>=2),n>e.lookahead&&(n=e.lookahead);do{if(h[(i=t)+a]===m&&h[i+a-1]===p&&h[i]===h[o]&&h[++i]===h[o+1]){o+=2,i++;do{}while(h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&oa){if(e.match_start=t,a=s,s>=n)break;p=h[o+a-1],m=h[o+a]}}}while((t=d[t&c])>l&&0!=--r);return a<=e.lookahead?a:e.lookahead}function oe(e){var t,i,s,o,l,h,c,d,u,p,m=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=m+(m-N)){r.arraySet(e.window,e.window,m,m,0),e.match_start-=m,e.strstart-=m,e.block_start-=m,t=i=e.hash_size;do{s=e.head[--t],e.head[t]=s>=m?s-m:0}while(--i);t=i=m;do{s=e.prev[--t],e.prev[t]=s>=m?s-m:0}while(--i);o+=m}if(0===e.strm.avail_in)break;if(h=e.strm,c=e.window,d=e.strstart+e.lookahead,u=o,p=void 0,(p=h.avail_in)>u&&(p=u),i=0===p?0:(h.avail_in-=p,r.arraySet(c,h.input,h.next_in,p,d),1===h.state.wrap?h.adler=a(h.adler,c,p,d):2===h.state.wrap&&(h.adler=n(h.adler,c,p,d)),h.next_in+=p,h.total_in+=p,p),e.lookahead+=i,e.lookahead+e.insert>=I)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<=I&&(e.ins_h=(e.ins_h<=I)if(s=o._tr_tally(e,e.strstart-e.match_start,e.match_length-I),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=I){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=I&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=I-1)),e.prev_length>=I&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-I,s=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-I),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=(e.ins_h<15&&(n=2,s-=16),o<1||o>C||i!==A||s<8||s>15||t<0||t>9||a<0||a>P)return Z(e,f);8===s&&(s=9);var l=new function(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=A,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new r.Buf16(2*k),this.dyn_dtree=new r.Buf16(2*(2*D+1)),this.bl_tree=new r.Buf16(2*(2*T+1)),J(this.dyn_ltree),J(this.dyn_dtree),J(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new r.Buf16(B+1),this.heap=new r.Buf16(2*L+1),J(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(2*L+1),J(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0};return e.state=l,l.strm=e,l.wrap=n,l.gzhead=null,l.w_bits=s,l.w_size=1<e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(oe(e),0===e.lookahead&&t===h)return W;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var s=e.block_start+i;if((0===e.strstart||e.strstart>=s)&&(e.lookahead=e.strstart-s,e.strstart=s,te(e,!1),0===e.strm.avail_out))return W;if(e.strstart-e.block_start>=e.w_size-N&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):(e.strstart>e.block_start&&(te(e,!1),e.strm.avail_out),W)}),new le(4,4,8,4,ae),new le(4,5,16,8,ae),new le(4,6,32,32,ae),new le(4,4,16,16,ne),new le(8,16,32,32,ne),new le(8,16,128,128,ne),new le(8,32,128,256,ne),new le(32,128,258,1024,ne),new le(32,258,258,4096,ne)],i.deflateInit=function(e,t){return de(e,t,A,R,S,x)},i.deflateInit2=de,i.deflateReset=ce,i.deflateResetKeep=he,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?f:(e.state.gzhead=t,m):f},i.deflate=function(e,t){var i,r,a,l;if(!e||!e.state||t>p||t<0)return e?Z(e,f):f;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||r.status===$&&t!==u)return Z(e,0===e.avail_out?v:f);if(r.strm=e,i=r.last_flush,r.last_flush=t,r.status===O)if(2===r.wrap)e.adler=0,ie(r,31),ie(r,139),ie(r,8),r.gzhead?(ie(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),ie(r,255&r.gzhead.time),ie(r,r.gzhead.time>>8&255),ie(r,r.gzhead.time>>16&255),ie(r,r.gzhead.time>>24&255),ie(r,9===r.level?2:r.strategy>=M||r.level<2?4:0),ie(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(ie(r,255&r.gzhead.extra.length),ie(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=n(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=j):(ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,9===r.level?2:r.strategy>=M||r.level<2?4:0),ie(r,K),r.status=H);else{var g=A+(r.w_bits-8<<4)<<8;g|=(r.strategy>=M||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(g|=V),g+=31-g%31,r.status=H,se(r,g),0!==r.strstart&&(se(r,e.adler>>>16),se(r,65535&e.adler)),e.adler=1}if(r.status===j)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending!==r.pending_buf_size));)ie(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=U)}else r.status=U;if(r.status===U)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindexa&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.gzindex=0,r.status=G)}else r.status=G;if(r.status===G)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindexa&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.status=z)}else r.status=z;if(r.status===z&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&ee(e),r.pending+2<=r.pending_buf_size&&(ie(r,255&e.adler),ie(r,e.adler>>8&255),e.adler=0,r.status=H)):r.status=H),0!==r.pending){if(ee(e),0===e.avail_out)return r.last_flush=-1,m}else if(0===e.avail_in&&Q(t)<=Q(i)&&t!==u)return Z(e,v);if(r.status===$&&0!==e.avail_in)return Z(e,v);if(0!==e.avail_in||0!==r.lookahead||t!==h&&r.status!==$){var b=r.strategy===M?function(e,t){for(var i;;){if(0===e.lookahead&&(oe(e),0===e.lookahead)){if(t===h)return W;break}if(e.match_length=0,i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?W:X}(r,t):r.strategy===w?function(e,t){for(var i,s,r,a,n=e.window;;){if(e.lookahead<=F){if(oe(e),e.lookahead<=F&&t===h)return W;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=I&&e.strstart>0&&(s=n[r=e.strstart-1])===n[++r]&&s===n[++r]&&s===n[++r]){a=e.strstart+F;do{}while(s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=I?(i=o._tr_tally(e,1,e.match_length-I),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?W:X}(r,t):s[r.level].func(r,t);if(b!==Y&&b!==q||(r.status=$),b===W||b===Y)return 0===e.avail_out&&(r.last_flush=-1),m;if(b===X&&(t===c?o._tr_align(r):t!==p&&(o._tr_stored_block(r,0,0,!1),t===d&&(J(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),ee(e),0===e.avail_out))return r.last_flush=-1,m}return t!==u?m:r.wrap<=0?_:(2===r.wrap?(ie(r,255&e.adler),ie(r,e.adler>>8&255),ie(r,e.adler>>16&255),ie(r,e.adler>>24&255),ie(r,255&e.total_in),ie(r,e.total_in>>8&255),ie(r,e.total_in>>16&255),ie(r,e.total_in>>24&255)):(se(r,e.adler>>>16),se(r,65535&e.adler)),ee(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?m:_)},i.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==O&&t!==j&&t!==U&&t!==G&&t!==z&&t!==H&&t!==$?Z(e,f):(e.state=null,t===H?Z(e,g):m):f},i.deflateSetDictionary=function(e,t){var i,s,o,n,l,h,c,d,u=t.length;if(!e||!e.state)return f;if(2===(n=(i=e.state).wrap)||1===n&&i.status!==O||i.lookahead)return f;for(1===n&&(e.adler=a(e.adler,t,u,0)),i.wrap=0,u>=i.w_size&&(0===n&&(J(i.head),i.strstart=0,i.block_start=0,i.insert=0),d=new r.Buf8(i.w_size),r.arraySet(d,t,u-i.w_size,i.w_size,0),t=d,u=i.w_size),l=e.avail_in,h=e.next_in,c=e.input,e.avail_in=u,e.next_in=0,e.input=t,oe(i);i.lookahead>=I;){s=i.strstart,o=i.lookahead-(I-1);do{i.ins_h=(i.ins_h<>>=y=b>>>24,m-=y,0===(y=b>>>16&255))A[o++]=65535&b;else{if(!(16&y)){if(0==(64&y)){b=_[(65535&b)+(p&(1<>>=y,m-=y),m<15&&(p+=E[s++]<>>=y=b>>>24,m-=y,!(16&(y=b>>>16&255))){if(0==(64&y)){b=f[(65535&b)+(p&(1<l){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=y,m-=y,w>(y=o-a)){if((y=w-y)>c&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(P=0,x=u,0===d){if(P+=h-y,y2;)A[o++]=x[P++],A[o++]=x[P++],A[o++]=x[P++],M-=3;M&&(A[o++]=x[P++],M>1&&(A[o++]=x[P++]))}else{P=o-w;do{A[o++]=A[P++],A[o++]=A[P++],A[o++]=A[P++],M-=3}while(M>2);M&&(A[o++]=A[P++],M>1&&(A[o++]=A[P++]))}break}}break}}while(s>3,p&=(1<<(m-=M<<3))-1,e.next_in=s,e.next_out=o,e.avail_in=s>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function re(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=w,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(ee),t.distcode=t.distdyn=new s.Buf32(te),t.sane=1,t.back=-1,m):g}function oe(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,re(e)):g}function ae(e,t){var i,s;return e&&e.state?(s=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?g:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,oe(e))):g}function ne(e,t){var i,r;return e?(r=new function(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0},e.state=r,r.window=null,(i=ae(e,t))!==m&&(e.state=null),i):g}var le,he,ce=!0;function de(e){if(ce){var t;for(le=new s.Buf32(512),he=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(n(h,e.lens,0,288,le,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;n(c,e.lens,0,32,he,0,e.work,{bits:5}),ce=!1}e.lencode=le,e.lenbits=9,e.distcode=he,e.distbits=5}function ue(e,t,i,r){var o,a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(s.arraySet(a.window,t,i-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((o=a.wsize-a.wnext)>r&&(o=r),s.arraySet(a.window,t,i-r,o,a.wnext),(r-=o)?(s.arraySet(a.window,t,i-r,r,0),a.wnext=r,a.whave=a.wsize):(a.wnext+=o,a.wnext===a.wsize&&(a.wnext=0),a.whave>>8&255,i.check=o(i.check,Ce,2,0),ne=0,le=0,i.mode=P;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&ne)<<8)+(ne>>8))%31){e.msg="incorrect header check",i.mode=Z;break}if((15&ne)!==M){e.msg="unknown compression method",i.mode=Z;break}if(le-=4,we=8+(15&(ne>>>=4)),0===i.wbits)i.wbits=we;else if(we>i.wbits){e.msg="invalid window size",i.mode=Z;break}i.dmax=1<>8&1),512&i.flags&&(Ce[0]=255&ne,Ce[1]=ne>>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0,i.mode=x;case x:for(;le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>8&255,Ce[2]=ne>>>16&255,Ce[3]=ne>>>24&255,i.check=o(i.check,Ce,4,0)),ne=0,le=0,i.mode=E;case E:for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<>8),512&i.flags&&(Ce[0]=255&ne,Ce[1]=ne>>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0,i.mode=A;case A:if(1024&i.flags){for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0}else i.head&&(i.head.extra=null);i.mode=C;case C:if(1024&i.flags&&((pe=i.length)>oe&&(pe=oe),pe&&(i.head&&(we=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),s.arraySet(i.head.extra,ee,ie,pe,we)),512&i.flags&&(i.check=o(i.check,ee,pe,ie)),oe-=pe,ie+=pe,i.length-=pe),i.length))break e;i.length=0,i.mode=R;case R:if(2048&i.flags){if(0===oe)break e;pe=0;do{we=ee[ie+pe++],i.head&&we&&i.length<65536&&(i.head.name+=String.fromCharCode(we))}while(we&&pe>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=k;break;case D:for(;le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=7&le,le-=7&le,i.mode=Y;break}for(;le<3;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=1)){case 0:i.mode=I;break;case 1:if(de(i),i.mode=U,t===p){ne>>>=2,le-=2;break e}break;case 2:i.mode=V;break;case 3:e.msg="invalid block type",i.mode=Z}ne>>>=2,le-=2;break;case I:for(ne>>>=7&le,le-=7≤le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Z;break}if(i.length=65535&ne,ne=0,le=0,i.mode=F,t===p)break e;case F:i.mode=N;case N:if(pe=i.length){if(pe>oe&&(pe=oe),pe>ae&&(pe=ae),0===pe)break e;s.arraySet(te,ee,ie,pe,re),oe-=pe,ie+=pe,ae-=pe,re+=pe,i.length-=pe;break}i.mode=k;break;case V:for(;le<14;){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=5,le-=5,i.ndist=1+(31&ne),ne>>>=5,le-=5,i.ncode=4+(15&ne),ne>>>=4,le-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Z;break}i.have=0,i.mode=O;case O:for(;i.have>>=3,le-=3}for(;i.have<19;)i.lens[Re[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,xe={bits:i.lenbits},Pe=n(l,i.lens,0,19,i.lencode,0,i.work,xe),i.lenbits=xe.bits,Pe){e.msg="invalid code lengths set",i.mode=Z;break}i.have=0,i.mode=j;case j:for(;i.have>>16&255,ve=65535&Ae,!((fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=fe,le-=fe,i.lens[i.have++]=ve;else{if(16===ve){for(Ee=fe+2;le>>=fe,le-=fe,0===i.have){e.msg="invalid bit length repeat",i.mode=Z;break}we=i.lens[i.have-1],pe=3+(3&ne),ne>>>=2,le-=2}else if(17===ve){for(Ee=fe+3;le>>=fe)),ne>>>=3,le-=3}else{for(Ee=fe+7;le>>=fe)),ne>>>=7,le-=7}if(i.have+pe>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Z;break}for(;pe--;)i.lens[i.have++]=we}}if(i.mode===Z)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Z;break}if(i.lenbits=9,xe={bits:i.lenbits},Pe=n(h,i.lens,0,i.nlen,i.lencode,0,i.work,xe),i.lenbits=xe.bits,Pe){e.msg="invalid literal/lengths set",i.mode=Z;break}if(i.distbits=6,i.distcode=i.distdyn,xe={bits:i.distbits},Pe=n(c,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,xe),i.distbits=xe.bits,Pe){e.msg="invalid distances set",i.mode=Z;break}if(i.mode=U,t===p)break e;case U:i.mode=G;case G:if(oe>=6&&ae>=258){e.next_out=re,e.avail_out=ae,e.next_in=ie,e.avail_in=oe,i.hold=ne,i.bits=le,a(e,ce),re=e.next_out,te=e.output,ae=e.avail_out,ie=e.next_in,ee=e.input,oe=e.avail_in,ne=i.hold,le=i.bits,i.mode===k&&(i.back=-1);break}for(i.back=0;ge=(Ae=i.lencode[ne&(1<>>16&255,ve=65535&Ae,!((fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>be)])>>>16&255,ve=65535&Ae,!(be+(fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=be,le-=be,i.back+=be}if(ne>>>=fe,le-=fe,i.back+=fe,i.length=ve,0===ge){i.mode=X;break}if(32&ge){i.back=-1,i.mode=k;break}if(64&ge){e.msg="invalid literal/length code",i.mode=Z;break}i.extra=15&ge,i.mode=z;case z:if(i.extra){for(Ee=i.extra;le>>=i.extra,le-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=H;case H:for(;ge=(Ae=i.distcode[ne&(1<>>16&255,ve=65535&Ae,!((fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>be)])>>>16&255,ve=65535&Ae,!(be+(fe=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<>>=be,le-=be,i.back+=be}if(ne>>>=fe,le-=fe,i.back+=fe,64&ge){e.msg="invalid distance code",i.mode=Z;break}i.offset=ve,i.extra=15&ge,i.mode=$;case $:if(i.extra){for(Ee=i.extra;le>>=i.extra,le-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Z;break}i.mode=W;case W:if(0===ae)break e;if(pe=ce-ae,i.offset>pe){if((pe=i.offset-pe)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Z;break}pe>i.wnext?(pe-=i.wnext,me=i.wsize-pe):me=i.wnext-pe,pe>i.length&&(pe=i.length),_e=i.window}else _e=te,me=re-i.offset,pe=i.length;pe>ae&&(pe=ae),ae-=pe,i.length-=pe;do{te[re++]=_e[me++]}while(--pe);0===i.length&&(i.mode=G);break;case X:if(0===ae)break e;te[re++]=i.length,ae--,i.mode=G;break;case Y:if(i.wrap){for(;le<32;){if(0===oe)break e;oe--,ne|=ee[ie++]<=1&&0===I[A];A--);if(C>A&&(C=A),0===A)return h[c++]=20971520,h[c++]=20971520,u.bits=1,0;for(E=1;E0&&(0===e||1!==A))return-1;for(F[1]=0,P=1;P<15;P++)F[P+1]=F[P]+I[P];for(x=0;x852||2===e&&D>592)return 1;for(;;){b=P-S,d[x]v?(y=N[V+d[x]],M=k[B+d[x]]):(y=96,M=0),p=1<>S)+(m-=p)]=b<<24|y<<16|M|0}while(0!==m);for(p=1<>=1;if(0!==p?(T&=p-1,T+=p):T=0,x++,0==--I[P]){if(P===A)break;P=t[i+d[x]]}if(P>C&&(T&f)!==_){for(0===S&&(S=C),g+=E,L=1<<(R=P-S);R+S852||2===e&&D>592)return 1;h[_=T&f]=C<<24|R<<16|g-c|0}}return 0!==T&&(h[g+T]=P-S<<24|64<<16|0),u.bits=C,0}},{"../utils/common":3}],13:[function(e,t,i){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],14:[function(e,t,i){var s=e("../utils/common"),r=4,o=0,a=1,n=2;function l(e){for(var t=e.length;--t>=0;)e[t]=0}var h=0,c=1,d=2,u=29,p=256,m=p+1+u,_=30,f=19,g=2*m+1,v=15,b=16,y=7,M=256,w=16,P=17,x=18,E=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],A=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],C=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],R=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S=new Array(2*(m+2));l(S);var L=new Array(2*_);l(L);var D=new Array(512);l(D);var T=new Array(256);l(T);var k=new Array(u);l(k);var B,I,F,N=new Array(_);function V(e,t,i,s,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=s,this.max_length=r,this.has_stree=e&&e.length}function O(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function j(e){return e<256?D[e]:D[256+(e>>>7)]}function U(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function G(e,t,i){e.bi_valid>b-i?(e.bi_buf|=t<>b-e.bi_valid,e.bi_valid+=i-b):(e.bi_buf|=t<>>=1,i<<=1}while(--t>0);return i>>>1}function $(e,t,i){var s,r,o=new Array(v+1),a=0;for(s=1;s<=v;s++)o[s]=a=a+i[s-1]<<1;for(r=0;r<=t;r++){var n=e[2*r+1];0!==n&&(e[2*r]=H(o[n]++,n))}}function W(e){var t;for(t=0;t8?U(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Y(e,t,i,s){var r=2*t,o=2*i;return e[r]>1;i>=1;i--)q(e,o,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],q(e,o,1),s=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=s,o[2*r]=o[2*i]+o[2*s],e.depth[r]=(e.depth[i]>=e.depth[s]?e.depth[i]:e.depth[s])+1,o[2*i+1]=o[2*s+1]=r,e.heap[1]=r++,q(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,s,r,o,a,n,l=t.dyn_tree,h=t.max_code,c=t.stat_desc.static_tree,d=t.stat_desc.has_stree,u=t.stat_desc.extra_bits,p=t.stat_desc.extra_base,m=t.stat_desc.max_length,_=0;for(o=0;o<=v;o++)e.bl_count[o]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;im&&(o=m,_++),l[2*s+1]=o,s>h||(e.bl_count[o]++,a=0,s>=p&&(a=u[s-p]),n=l[2*s],e.opt_len+=n*(o+a),d&&(e.static_len+=n*(c[2*s+1]+a)));if(0!==_){do{for(o=m-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[m]--,_-=2}while(_>0);for(o=m;0!==o;o--)for(s=e.bl_count[o];0!==s;)(r=e.heap[--i])>h||(l[2*r+1]!==o&&(e.opt_len+=(o-l[2*r+1])*l[2*r],l[2*r+1]=o),s--)}}(e,t),$(o,h,e.bl_count)}function Q(e,t,i){var s,r,o=-1,a=t[1],n=0,l=7,h=4;for(0===a&&(l=138,h=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=a,a=t[2*(s+1)+1],++n>=7;s<_;s++)for(N[s]=r<<7,e=0;e<1<0?(e.strm.data_type===n&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return o;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return a;for(t=32;t=3&&0===e.bl_tree[2*R[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),l=e.opt_len+3+7>>>3,(h=e.static_len+3+7>>>3)<=l&&(l=h)):l=h=i+5,i+4<=l&&-1!==t?te(e,t,i,s):e.strategy===r||h===l?(G(e,(c<<1)+(s?1:0),3),K(e,S,L)):(G(e,(d<<1)+(s?1:0),3),function(e,t,i,s){var r;for(G(e,t-257,5),G(e,i-1,5),G(e,s-4,4),r=0;r>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(T[i]+p+1)]++,e.dyn_dtree[2*j(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){G(e,c<<1,3),z(e,M,S),function(e){16===e.bi_valid?(U(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":3}],15:[function(e,t,i){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/":[function(e,t,i){var s={};(0,e("./lib/utils/common").assign)(s,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=s},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")});var p=Object.freeze({__proto__:null});let pako=window.pako||p;pako.inflate||(pako=pako.default);const decompressColor=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function extract(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],positionsDecodeMatrix:e[11]}}function inflate(e){return{positions:new Uint16Array(pako.inflate(e.positions).buffer),normals:new Int8Array(pako.inflate(e.normals).buffer),indices:new Uint32Array(pako.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(pako.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(pako.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(pako.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(pako.inflate(e.meshColors).buffer),entityIDs:pako.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(pako.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(pako.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(pako.inflate(e.positionsDecodeMatrix).buffer)}}function load(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.meshPositions,h=i.meshIndices,c=i.meshEdgesIndices,d=i.meshColors,u=JSON.parse(i.entityIDs),p=i.entityMeshes,m=i.entityIsObjects,_=l.length,f=p.length;for(let g=0;gp[e]p[t]?1:0);for(let e=0;e1||(x[i]=e)}}for(let e=0;e1,_=decompressColor$3(m.subarray(4*t,4*t+3)),g=m[4*t+3]/255,v=r.subarray(c[t],i?r.length:c[t+1]),y=o.subarray(c[t],i?o.length:c[t+1]),P=a.subarray(d[t],i?a.length:d[t+1]),A=n.subarray(u[t],i?n.length:u[t+1]),C=l.subarray(p[t],p[t]+16);if(h){var E="geometry"+t;s.createGeometry({id:E,primitive:"triangles",positions:v,normals:y,indices:P,edgeIndices:A,positionsDecodeMatrix:C})}else{const e=t,i=(f[x[t]],{});s.createMesh(utils.apply(i,{id:e,primitive:"triangles",positions:v,normals:y,indices:P,edgeIndices:A,positionsDecodeMatrix:C,color:_,opacity:g}))}}let A=0;for(let e=0;e1){const t={},r="instance."+A++,o="geometry"+i,a=16*v[e],l=h.subarray(a,a+16);s.createMesh(utils.apply(t,{id:r,geometryId:o,matrix:l})),n.push(r)}else n.push(i)}if(n.length>0){const e={};s.createEntity(utils.apply(e,{id:r,isObject:!0,meshIds:n}))}}}const ParserV4={version:4,parse:function(e,t,i,s){load$3(e,t,inflate$3(extract$3(i)),s)}};let pako$4=window.pako||p;function extract$4(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],eachPrimitivePositionsAndNormalsPortion:e[5],eachPrimitiveIndicesPortion:e[6],eachPrimitiveEdgeIndicesPortion:e[7],eachPrimitiveColor:e[8],primitiveInstances:e[9],eachEntityId:e[10],eachEntityPrimitiveInstancesPortion:e[11],eachEntityMatricesPortion:e[12]}}function inflate$4(e){return{positions:new Float32Array(pako$4.inflate(e.positions).buffer),normals:new Int8Array(pako$4.inflate(e.normals).buffer),indices:new Uint32Array(pako$4.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako$4.inflate(e.edgeIndices).buffer),matrices:new Float32Array(pako$4.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(pako$4.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(pako$4.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(pako$4.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(pako$4.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(pako$4.inflate(e.primitiveInstances).buffer),eachEntityId:pako$4.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(pako$4.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(pako$4.inflate(e.eachEntityMatricesPortion).buffer)}}pako$4.inflate||(pako$4=pako$4.default);const decompressColor$4=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function load$4(e,t,i,s){s.positionsCompression="disabled",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.matrices,h=i.eachPrimitivePositionsAndNormalsPortion,c=i.eachPrimitiveIndicesPortion,d=i.eachPrimitiveEdgeIndicesPortion,u=i.eachPrimitiveColor,p=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,f=i.eachEntityMatricesPortion,g=h.length,v=p.length,b=new Uint8Array(g),y=m.length;for(let e=0;e1||(M[i]=e)}}for(let e=0;e1,l=decompressColor$4(u.subarray(4*e,4*e+3)),p=u[4*e+3]/255,_=r.subarray(h[e],t?r.length:h[e+1]),f=o.subarray(h[e],t?o.length:h[e+1]),v=a.subarray(c[e],t?a.length:c[e+1]),y=n.subarray(d[e],t?n.length:d[e+1]);if(i){var w="geometry"+e;s.createGeometry({id:w,primitive:"triangles",positions:_,normals:f,indices:v,edgeIndices:y})}else{const t=e,i=(m[M[e]],{});s.createMesh(utils.apply(i,{id:t,primitive:"triangles",positions:_,normals:f,indices:v,edgeIndices:y,color:l,opacity:p}))}}let P=0;for(let e=0;e1){const t={},r="instance."+P++,o="geometry"+i,a=16*f[e],h=l.subarray(a,a+16);s.createMesh(utils.apply(t,{id:r,geometryId:o,matrix:h})),n.push(r)}else n.push(i)}if(n.length>0){const e={};s.createEntity(utils.apply(e,{id:r,isObject:!0,meshIds:n}))}}}const ParserV5={version:5,parse:function(e,t,i,s){load$4(e,t,inflate$4(extract$4(i)),s)}};let pako$5=window.pako||p;function extract$5(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}function inflate$5(e){return{positions:new Uint16Array(pako$5.inflate(e.positions).buffer),normals:new Int8Array(pako$5.inflate(e.normals).buffer),indices:new Uint32Array(pako$5.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako$5.inflate(e.edgeIndices).buffer),matrices:new Float32Array(pako$5.inflate(e.matrices).buffer),reusedPrimitivesDecodeMatrix:new Float32Array(pako$5.inflate(e.reusedPrimitivesDecodeMatrix).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(pako$5.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(pako$5.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(pako$5.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColorAndOpacity:new Uint8Array(pako$5.inflate(e.eachPrimitiveColorAndOpacity).buffer),primitiveInstances:new Uint32Array(pako$5.inflate(e.primitiveInstances).buffer),eachEntityId:pako$5.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(pako$5.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(pako$5.inflate(e.eachEntityMatricesPortion).buffer),eachTileAABB:new Float64Array(pako$5.inflate(e.eachTileAABB).buffer),eachTileEntitiesPortion:new Uint32Array(pako$5.inflate(e.eachTileEntitiesPortion).buffer)}}pako$5.inflate||(pako$5=pako$5.default);const decompressColor$5=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function load$5(e,t,i,s){const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.matrices,h=i.reusedPrimitivesDecodeMatrix,c=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,u=i.eachPrimitiveEdgeIndicesPortion,p=i.eachPrimitiveColorAndOpacity,m=i.primitiveInstances,_=JSON.parse(i.eachEntityId),f=i.eachEntityPrimitiveInstancesPortion,g=i.eachEntityMatricesPortion,v=i.eachTileAABB,b=i.eachTileEntitiesPortion,y=c.length,M=m.length,w=_.length,P=b.length;let x=0;const E=new Uint32Array(y);for(let e=0;e1,_=t===y-1,f=r.subarray(c[t],_?r.length:c[t+1]),g=o.subarray(c[t],_?o.length:c[t+1]),v=a.subarray(d[t],_?a.length:d[t+1]),b=n.subarray(u[t],_?n.length:u[t+1]),M=decompressColor$5(p.subarray(4*t,4*t+3)),w=p[4*t+3]/255,C=x++;if(l){const e="geometry."+i+"."+t;k[e]||(s.createGeometry({id:e,rtcCenter:A,primitive:"triangles",positions:f,normals:g,indices:v,edgeIndices:b,positionsDecodeMatrix:h}),k[e]=!0),s.createMesh(utils.apply(I,{id:C,geometryId:e,matrix:P,color:M,opacity:w})),L.push(C)}else s.createMesh(utils.apply(I,{id:C,rtcCenter:A,primitive:"triangles",positions:f,normals:g,indices:v,edgeIndices:b,positionsDecodeMatrix:T,color:M,opacity:w})),L.push(C)}L.length>0&&s.createEntity(utils.apply(B,{id:b,isObject:!0,meshIds:L}))}}}const ParserV6={version:6,parse:function(e,t,i,s){load$5(e,t,inflate$5(extract$5(i)),s)}},parsers={};parsers[ParserV1.version]=ParserV1,parsers[ParserV2.version]=ParserV2,parsers[ParserV3.version]=ParserV3,parsers[ParserV4.version]=ParserV4,parsers[ParserV5.version]=ParserV5,parsers[ParserV6.version]=ParserV6;class XKTLoaderPlugin extends Plugin{constructor(e,t={}){super("XKTLoader",e,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults,this.includeTypes=t.includeTypes,this.excludeTypes=t.excludeTypes,this.excludeUnclassifiedObjects=t.excludeUnclassifiedObjects}get supportedVersions(){return Object.keys(parsers)}set dataSource(e){this._dataSource=e||new XKTDefaultDataSource}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||IFCObjectDefaults}get objectDefaults(){return this._objectDefaults}set includeTypes(e){this._includeTypes=e}get includeTypes(){return this._includeTypes}set excludeTypes(e){this._excludeTypes=e}get excludeTypes(){return this._excludeTypes}set excludeUnclassifiedObjects(e){this._excludeUnclassifiedObjects=!!e}get excludeUnclassifiedObjects(){return this._excludeUnclassifiedObjects}load(e={}){e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);const t=new PerformanceModel(this.viewer.scene,utils.apply(e,{isModel:!0})),i=t.id;if(!e.src&&!e.xkt)return this.error("load() param expected: src or xkt"),t;const s={};if(e.metaModelSrc||e.metaModelData){const r=e.includeTypes||this._includeTypes,o=e.excludeTypes||this._excludeTypes,a=e.objectDefaults||this._objectDefaults;if(r){s.includeTypesMap={};for(let e=0,t=r.length;e{this.viewer.metaScene.createMetaModel(i,a,{includeTypes:r,excludeTypes:o}),this.viewer.scene.canvas.spinner.processes--,e.src?this._loadModel(e.src,e,s,t):this._parseModel(e.xkt,e,s,t),t.once("destroyed",()=>{this.viewer.metaScene.destroyMetaModel(t.id)})};if(e.metaModelSrc){const t=e.metaModelSrc;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getMetaModel(t,e=>{this.viewer.scene.canvas.spinner.processes--,n(e)},e=>{this.error(`load(): Failed to load model metadata for model '${i} from '${t}' - ${e}`),this.viewer.scene.canvas.spinner.processes--})}else e.metaModelData&&n(e.metaModelData)}else e.src?this._loadModel(e.src,e,s,t):this._parseModel(e.xkt,e,s,t);return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getXKT(t.src,e=>{this._parseModel(e,t,i,s),r.processes--},e=>{r.processes--,this.error(e),s.fire("error",e)})}_parseModel(e,t,i,s){const r=new DataView(e),o=new Uint8Array(e),a=r.getUint32(0,!0),n=parsers[a];if(!n)return void this.error("Unsupported .XKT file version: "+a+" - this XKTLoaderPlugin supports versions "+Object.keys(parsers));this.log("Loading .xkt V"+a);const l=r.getUint32(4,!0),h=[];let c=4*(l+2);for(let e=0;e{s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1)})}}const ModelIFCObjectColors={IfcSpace:{opacity:.3},IfcWindow:{opacity:.4},IfcOpeningElement:{opacity:.3},IfcPlate:{opacity:.3}},ViewerIFCObjectColors={IfcRoof:{colorize:[.837255,.203922,.270588],priority:0},IfcSlab:{colorize:[.637255,.603922,.670588],priority:0},IfcWall:{colorize:[.537255,.337255,.237255],priority:0},IfcWallStandardCase:{colorize:[.537255,.337255,.237255],priority:0},IfcCovering:{colorize:[.8470588235,.427450980392,0],priority:0},IfcDoor:{colorize:[.637255,.603922,.670588],priority:1},IfcStair:{colorize:[.637255,.603922,.670588],priority:2},IfcStairFlight:{colorize:[.637255,.603922,.670588],priority:2},IfcProxy:{colorize:[.137255,.403922,.870588],priority:2},IfcRamp:{colorize:[.8470588235,.427450980392,0],priority:2},IfcColumn:{colorize:[.137255,.403922,.870588],priority:3},IfcBeam:{colorize:[.137255,.403922,.870588],priority:3},IfcCurtainWall:{colorize:[.137255,.403922,.870588],priority:3},IfcPlate:{colorize:[.8470588235,.427450980392,0,.5],opacity:.5,priority:3},IfcTransportElement:{colorize:[.8470588235,.427450980392,0],priority:3},IfcFooting:{colorize:[.8470588235,.427450980392,0],priority:3},IfcRailing:{colorize:[.137255,.403922,.870588],priority:4},IfcFurnishingElement:{colorize:[.137255,.403922,.870588],priority:4},IfcFurniture:{colorize:[.8470588235,.427450980392,0],priority:4},IfcSystemFurnitureElement:{colorize:[.8470588235,.427450980392,0],priority:4},IfcFlowSegment:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowitting:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowTerminal:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowController:{colorize:[.8470588235,.427450980392,0],priority:5},IfcFlowFitting:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDuctSegment:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDistributionFlowElement:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDuctFitting:{colorize:[.8470588235,.427450980392,0],priority:5},IfcLightFixture:{colorize:[.8470588235,.8470588235,.870588],priority:5},IfcAirTerminal:{colorize:[.8470588235,.427450980392,0],priority:6},IfcOpeningElement:{colorize:[.137255,.403922,.870588],opacity:.3,priority:6},IfcSpace:{colorize:[.137255,.403922,.870588],opacity:.5,priority:6},IfcWindow:{colorize:[.137255,.403922,.870588],opacity:.4,priority:6},IfcBuildingElementProxy:{colorize:[.5,.5,.5]},IfcSite:{colorize:[.137255,.403922,.870588]},IfcMember:{colorize:[.8470588235,.427450980392,0]},DEFAULT:{colorize:[.5,.5,.5],priority:10}};class ModelsContextMenu extends ContextMenu{constructor(e={}){const t=[[{title:"Load",getEnabled:function(e){return!e.bimViewer.isModelLoaded(e.modelId)},doAction:function(e){e.bimViewer.loadModel(e.modelId)}},{title:"Unload",getEnabled:function(e){return e.bimViewer.isModelLoaded(e.modelId)},doAction:function(e){e.bimViewer.unloadModel(e.modelId)}}]];!!e.enableEditModels&&t.push([{title:"Edit",getEnabled:function(e){return!0},doAction:function(e){e.bimViewer.editModel(e.modelId)}},{title:"Delete",getEnabled:function(e){return!0},doAction:function(e){e.bimViewer.deleteModel(e.modelId)}}]),t.push([{title:"Load All",getEnabled:function(e){const t=e.bimViewer,i=t.getModelIds();return t.getLoadedModelIds().length0},doAction:function(e){e.bimViewer.unloadAllModels()}}]),t.push([{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]),super({context:e.context,items:t})}}const tempVec3$4=math.vec3();class ModelsExplorer extends Controller{constructor(e,t){if(super(e,t),!t.modelsTabElement)throw"Missing config: modelsTabElement";if(!t.unloadModelsButtonElement)throw"Missing config: unloadModelsButtonElement";if(!t.modelsElement)throw"Missing config: modelsElement";if(this._enableAddModels=!!t.enableEditModels,this._modelsTabElement=t.modelsTabElement,this._loadModelsButtonElement=t.loadModelsButtonElement,this._unloadModelsButtonElement=t.unloadModelsButtonElement,this._addModelButtonElement=t.addModelButtonElement,this._modelsElement=t.modelsElement,this._modelsTabButtonElement=this._modelsTabElement.querySelector(".xeokit-tab-btn"),!this._modelsTabButtonElement)throw"Missing DOM element: ,xeokit-tab-btn";this._xktLoader=new XKTLoaderPlugin(this.viewer,{objectDefaults:ModelIFCObjectColors}),this._modelsContextMenu=new ModelsContextMenu({enableEditModels:t.enableEditModels}),this._modelsInfo={},this._numModels=0,this._numModelsLoaded=0,this._projectId=null}loadProject(e,t,i){this.server.getProject(e,i=>{this.unloadProject(),this._projectId=e,this._modelsInfo={},this._numModels=0,this._parseProject(i,t),this._numModelsLoaded0&&this._unloadModelsButtonElement.classList.remove("disabled"),this._enableAddModels&&this._addModelButtonElement.classList.remove("disabled")},e=>{this.error(e),i&&i(e)})}_parseProject(e,t){this._buildModelsMenu(e),this._parseViewerConfigs(e),this._parseViewerContent(e,()=>{this._parseViewerState(e,()=>{t()})})}_buildModelsMenu(e){var t="";const i=e.models||[];this._modelsInfo={},this._numModels=i.length;for(let e=0,s=i.length;e",t+=""+s.name+"",t+=""}this._modelsElement.innerHTML=t;for(let e=0,t=i.length;e{r.checked?this.loadModel(s):this.unloadModel(t.id)}),o.addEventListener("click",()=>{!!this.viewer.scene.models[s]?this.unloadModel(t.id):this.loadModel(s)}),o.oncontextmenu=(e=>{this._modelsContextMenu.context={bimViewer:this.bimViewer,viewer:this.viewer,modelId:s},this._modelsContextMenu.show(e.pageX,e.pageY),e.preventDefault()})}}_parseViewerConfigs(e){const t=e.viewerConfigs;t&&this.bimViewer.setConfigs(t)}_parseViewerContent(e,t){const i=e.viewerContent;i?this._parseModelsLoaded(i,()=>{t()}):t()}_parseModelsLoaded(e,t){const i=e.modelsLoaded;i&&0!==i.length?this._loadNextModel(i.slice(0),t):t()}_loadNextModel(e,t){if(0===e.length)return void t();const i=e.pop();this.loadModel(i,()=>{this._loadNextModel(e,t)},()=>{this._loadNextModel(e,t)})}_parseViewerState(e,t){const i=e.viewerState;i?this.bimViewer.setViewerState(i,t):t()}unloadProject(){if(!this._projectId)return;const e=this.viewer.scene.models;for(var t in e)if(e.hasOwnProperty(t)){e[t].destroy()}this._modelsElement.innerHTML="",this._numModelsLoaded=0,this._loadModelsButtonElement.classList.add("disabled"),this._unloadModelsButtonElement.classList.add("disabled"),this._enableAddModels&&this._addModelButtonElement.classList.add("disabled");const i=this._projectId;this._projectId=null,this.fire("projectUnloaded",{projectId:i})}getLoadedProjectId(){return this._projectId}getModelIds(){return Object.keys(this._modelsInfo)}loadModel(e,t,i){if(!this._projectId){const e="No project currently loaded";return this.error(e),void(i&&i(e))}const s=this._modelsInfo[e];if(!s){const e="Model not in currently loaded project";return this.error(e),void(i&&i(e))}this.bimViewer._busyModal.show("Loading: "+s.name),this.server.getMetadata(this._projectId,e,r=>{this.server.getGeometry(this._projectId,e,i=>{const o="model"===(s.objectColorSource||this.bimViewer.getObjectColorSource())?ModelIFCObjectColors:ViewerIFCObjectColors;this._xktLoader.load({id:e,metaModelData:r,xkt:i,objectDefaults:o,excludeUnclassifiedObjects:!0,position:s.position,scale:s.scale,rotation:s.rotation,matrix:s.matrix,edges:!1!==s.edges,saoEnabled:s.saoEnabled}).on("loaded",()=>{document.getElementById(""+e).checked=!0;const i=this.viewer.scene,s=i.getAABB(i.visibleObjectIds);this._numModelsLoaded++,this._unloadModelsButtonElement.classList.remove("disabled"),this._numModelsLoaded{this.bimViewer._busyModal.hide(),this.error(e),i&&i(e)})},e=>{this.bimViewer._busyModal.hide(),this.error(e),i&&i(e)})}unloadModel(e){const t=this.viewer.scene.models[e];if(!t)return void this.error("Model not loaded: "+e);t.destroy(),document.getElementById(""+e).checked=!1;document.getElementById("span-"+e);this._numModelsLoaded--,this._numModelsLoaded>0?this._unloadModelsButtonElement.classList.remove("disabled"):this._unloadModelsButtonElement.classList.add("disabled"),this._numModelsLoaded{e.preventDefault()}),this._onObjectVisibility=this._viewer.scene.on("objectVisibility",e=>{if(this._muteSceneEvents)return;const t=e.id,i=this._objectNodes[t];if(!i)return;const s=e.visible;if(!(s!==i.checked))return;this._muteTreeEvents=!0,i.checked=s,s?i.numVisibleEntities++:i.numVisibleEntities--;const r=document.getElementById(i.nodeId);r&&(r.checked=s);let o=i.parent;for(;o;){o.checked=s,s?o.numVisibleEntities++:o.numVisibleEntities--;const e=document.getElementById(o.nodeId);if(e){const t=o.numVisibleEntities>0;t!==e.checked&&(e.checked=t)}o=o.parent}this._muteTreeEvents=!1}),this.switchExpandHandler=(e=>{e.preventDefault(),e.stopPropagation();const t=e.target;this._expandSwitchElement(t)}),this.switchCollapseHandler=(e=>{e.preventDefault(),e.stopPropagation();const t=e.target;this._collapseSwitchElement(t)}),this._checkboxChangeHandler=(e=>{if(this._muteTreeEvents)return;this._muteSceneEvents=!0;const t=e.target,i=t.checked,s=t.id,r=this._nodeToObjectID(s),o=this._objectNodes[r],a=this._viewer.scene.objects;let n=0;this._withNodeTree(o,e=>{const t=e.objectId,s=e.nodeId,r=a[t],o=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,o&&i!==e.checked&&n++,e.checked=i;const l=document.getElementById(s);l&&(l.checked=i),r&&(r.visible=i)});let l=o.parent;for(;l;){l.checked=i;const e=document.getElementById(l.nodeId);i?l.numVisibleEntities+=n:l.numVisibleEntities-=n;const t=l.numVisibleEntities>0;t!==e.checked&&(e.checked=t),l=l.parent}this._muteSceneEvents=!1}),this._hierarchy=r.hierarchy||"containment",this._autoExpandDepth=r.autoExpandDepth||0,this._createNodes())}_nodeToObjectID(e){return e.substring(this._baseId.length)}_objectToNodeID(e){return this._baseId+e}setAutoExpandDepth(e=0){this._autoExpandDepth=e}setHierarchy(e){this._hierarchy!==e&&(this._hierarchy=e,this._createNodes())}_createNodes(){switch(this._rootElement&&(this._rootElement.parentNode.removeChild(this._rootElement),this._rootElement=null),this._rootNodes=[],this._objectNodes={},this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this._treeViewPlugin.error("Failed to build storeys hierarchy for model '"+this._metaModel.id+"' - perhaps this model is not an IFC model?");break;case"types":this._createTypesNodes();break;case"containment":default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}_findEmptyNodes(e=this._rootMetaObject,t=0){const i=this._treeViewPlugin.viewer.scene,s=e.children,r=e.id,o=i.objects[r];if(e._countEntities=0,o&&e._countEntities++,s)for(let t=0,i=s.length;t{e.aabb&&r.aabb||(e.aabb||(e.aabb=t.getAABB(s.getObjectIDsInSubtree(e.objectId))),r.aabb||(r.aabb=t.getAABB(s.getObjectIDsInSubtree(r.objectId))));let o=0;return o=i.xUp?0:i.yUp?1:2,e.aabb[o]>r.aabb[o]?-1:e.aabb[o]s?1:0}_synchNodesToEntities(){const e=this._rootMetaObject.getObjectIDsInSubtree(),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects;for(let s=0,r=e.length;sthis._createNodeElement(e)),t=document.createElement("ul");e.forEach(e=>{t.appendChild(e)}),this._containerElement.appendChild(t),this._rootElement=t}_createNodeElement(e){const t=document.createElement("li"),i=e.nodeId;if(t.id="node-"+i,e.children.length>0){const e="switch-"+i,s=document.createElement("a");s.href="#",s.id=e,s.textContent="+",s.classList.add("plus"),s.addEventListener("click",this.switchExpandHandler),t.appendChild(s)}const s=document.createElement("input");s.id=i,s.type="checkbox",s.checked=e.checked,s.addEventListener("change",this._checkboxChangeHandler),t.appendChild(s);const r=document.createElement("span");return r.textContent=e.title,t.appendChild(r),r.oncontextmenu=(t=>{this._treeViewPlugin.fire("contextmenu",{event:t,viewer:this._viewer,treeViewPlugin:this._treeViewPlugin,treeViewNode:e}),t.preventDefault()}),r.onclick=(t=>{this._treeViewPlugin.fire("nodeTitleClicked",{event:t,viewer:this._viewer,treeViewPlugin:this._treeViewPlugin,treeViewNode:e}),t.preventDefault()}),t}expandToDepth(e){const t=(i,s)=>{if(s===e)return;const r="switch-"+i.nodeId,o=document.getElementById(r);if(o){this._expandSwitchElement(o);const e=i.children;for(var a=0,n=e.length;athis._createNodeElement(e)),o=document.createElement("ul");r.forEach(e=>{o.appendChild(e)}),t.appendChild(o),e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",this.switchExpandHandler),e.addEventListener("click",this.switchCollapseHandler)}_collapseNode(e){const t="switch-"+this._objectToNodeID(e),i=document.getElementById(t);this._collapseSwitchElement(i)}_collapseSwitchElement(e){if(!e)return;const t=e.parentElement;if(!t)return;const i=t.querySelector("ul");i&&(t.removeChild(i),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",this.switchCollapseHandler),e.addEventListener("click",this.switchExpandHandler))}destroy(){this._rootElement&&!this._destroyed&&(this._rootElement.parentNode.removeChild(this._rootElement),this._viewer.scene.off(this._onObjectVisibility),this._destroyed=!0,idMap$1.removeItem(this._id))}}class TreeViewPlugin extends Plugin{constructor(e,t={}){if(super("TreeViewPlugin",e),t.containerElement){if(this._containerElement=t.containerElement,this._modelTreeViews={},this._modelTreeViews={},this._autoAddModels=!1!==t.autoAddModels,this._autoExpandDepth=t.autoExpandDepth||0,this._sortNodes=!1!==t.sortNodes,this._pruneEmptyNodes=!1!==t.pruneEmptyNodes,this._autoAddModels){const e=Object.keys(this.viewer.scene.models);for(let t=0,i=e.length;t{this.viewer.metaScene.metaModels[e]&&this.addModel(e)})}this.hierarchy=t.hierarchy}else this.error("Config expected: containerElement")}set hierarchy(e){"containment"!==(e=e||"containment")&&"storeys"!==e&&"types"!==e&&(this.error("Unsupported value for `hierarchy' - defaulting to 'containment'"),e="containment"),this._hierarchy=e;for(let e in this._modelTreeViews)this._modelTreeViews.hasOwnProperty(e)&&this._modelTreeViews[e].setHierarchy(this._hierarchy)}get hierarchy(){return this._hierarchy}addModel(e,t={}){if(!this._containerElement)return;const i=this.viewer.scene.models[e];if(!i)throw"Model not found: "+e;const s=this.viewer.metaScene.metaModels[e];s?this._modelTreeViews[e]?this.warn("Model already added: "+e):(this._modelTreeViews[e]=new ModelTreeView(this.viewer,this,i,s,{containerElement:this._containerElement,autoExpandDepth:this._autoExpandDepth,hierarchy:this._hierarchy,sortNodes:this._sortNodes,pruneEmptyNodes:this._pruneEmptyNodes,rootName:t.rootName}),i.on("destroyed",()=>{this.removeModel(i.id)})):this.error("MetaModel not found: "+e)}removeModel(e){if(!this._containerElement)return;const t=this._modelTreeViews[e];t?(t.destroy(),delete this._modelTreeViews[e]):this.warn("Model not added: "+e)}collapse(){for(let e in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(e)){this._modelTreeViews[e].collapse()}}showNode(e){this.unShowNode();const t=this.viewer.metaScene.metaObjects[e];if(!t)return void this.error("MetaObject not found: "+e);const i=t.metaModel.id,s=this._modelTreeViews[i];s?s.showNode(e):this.error("Object not in this TreeView: "+e)}unShowNode(){for(let e in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(e)){this._modelTreeViews[e].unShowNode()}}expandToDepth(e){for(let t in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(t)){const i=this._modelTreeViews[t];i.collapse(),i.expandToDepth(e)}}withNodeTree(e,t){t(e);const i=e.children;if(i)for(let e=0,s=i.length;e{e.objectId&&s.push(e.objectId)});const r=i.getAABB(s);t.cameraControl.pivotPos=math.getAABB3Center(r,tempVec3$5),i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsVisible(i.objectIds,!1),i.setObjectsPickable(i.objectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsVisible(s,!0),i.setObjectsPickable(s,!0),t.cameraFlight.flyTo({aabb:r},()=>{})}}],[{title:"View Fit",doAction:function(e){const t=e.viewer,i=t.scene,s=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&s.push(e.objectId)}),i.setObjectsVisible(s,!0),i.setObjectsHighlighted(s,!0);const r=i.getAABB(s);t.cameraFlight.flyTo({aabb:r,duration:.5},()=>{setTimeout(function(){i.setObjectsHighlighted(i.highlightedObjectIds,!1)},500)}),t.cameraControl.pivotPos=math.getAABB3Center(r)}},{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}}],[{title:"Hide",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.visible=!1)}})}},{title:"Hide Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.visibleObjectIds,!1),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1),t.setObjectsHighlighted(t.highlightedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.visible=!0)}})}},{title:"Hide All",getEnabled:function(e){return e.viewer.scene.visibleObjectIds.length>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}}],[{title:"Show",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.visible=!0,i.xrayed&&(i.pickable=!0),i.xrayed=!1,i.selected=!1)}})}},{title:"Show Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.visible=!1)}})}},{title:"Show All",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.xrayed=!0,i.visible=!0,i.pickable=!1)}})}},{title:"Undo X-Ray",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.xrayed=!1,i.pickable=!0)}})}},{title:"X-Ray Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsHighlighted(t.highlightedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.xrayed=!1,i.pickable=!0)}})}},{title:"X-Ray All",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1)}},{title:"X-Ray None",getEnabled:function(e){return e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene,i=t.xrayedObjectIds;t.setObjectsPickable(i,!0),t.setObjectsXRayed(i,!1)}}],[{title:"Select",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!0,i.visible=!0)}})}},{title:"Undo Select",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!1)}})}},{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}const tempVec3$6=math.vec3();class ObjectsExplorer extends Controller{constructor(e,t={}){if(super(e),!t.objectsTabElement)throw"Missing config: objectsTabElement";if(!t.showAllObjectsButtonElement)throw"Missing config: showAllObjectsButtonElement";if(!t.hideAllObjectsButtonElement)throw"Missing config: hideAllObjectsButtonElement";if(!t.objectsElement)throw"Missing config: objectsElement";if(this._objectsTabElement=t.objectsTabElement,this._showAllObjectsButtonElement=t.showAllObjectsButtonElement,this._hideAllObjectsButtonElement=t.hideAllObjectsButtonElement,this._objectsTabButtonElement=this._objectsTabElement.querySelector(".xeokit-tab-btn"),!this._objectsTabButtonElement)throw"Missing DOM element: ,xeokit-tab-btn";const i=t.objectsElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,hierarchy:"containment",autoAddModels:!1,pruneEmptyNodes:!0}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{if(this.viewer.metaScene.metaModels[e]){const t=this.bimViewer._modelsExplorer.getModelInfo(e);if(!t)return;this._treeView.addModel(e,{rootName:t.name})}}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse()})}setEnabled(e){e?(this._objectsTabButtonElement.classList.remove("disabled"),this._showAllObjectsButtonElement.classList.remove("disabled"),this._hideAllObjectsButtonElement.classList.remove("disabled")):(this._objectsTabButtonElement.classList.add("disabled"),this._showAllObjectsButtonElement.classList.add("disabled"),this._hideAllObjectsButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$7=math.vec3();class ClassesExplorer extends Controller{constructor(e,t={}){if(super(e),!t.classesTabElement)throw"Missing config: classesTabElement";if(!t.showAllClassesButtonElement)throw"Missing config: showAllClassesButtonElement";if(!t.hideAllClassesButtonElement)throw"Missing config: hideAllClassesButtonElement";if(!t.classesElement)throw"Missing config: classesElement";if(this._classesTabElement=t.classesTabElement,this._showAllClassesButtonElement=t.showAllClassesButtonElement,this._hideAllClassesButtonElement=t.hideAllClassesButtonElement,this._classesTabButtonElement=this._classesTabElement.querySelector(".xeokit-tab-btn"),!this._classesTabButtonElement)throw"Missing DOM element: xeokit-tab-btn";const i=t.classesElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,hierarchy:"types",autoAddModels:!1,pruneEmptyNodes:!0}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{if(this.viewer.metaScene.metaModels[e]){const t=this.bimViewer._modelsExplorer.getModelInfo(e);if(!t)return;this._treeView.addModel(e,{rootName:t.name})}}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse()})}setEnabled(e){e?(this._classesTabButtonElement.classList.remove("disabled"),this._showAllClassesButtonElement.classList.remove("disabled"),this._hideAllClassesButtonElement.classList.remove("disabled")):(this._classesTabButtonElement.classList.add("disabled"),this._showAllClassesButtonElement.classList.add("disabled"),this._hideAllClassesButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$8=math.vec3();class StoreysExplorer extends Controller{constructor(e,t={}){if(super(e),!t.storeysTabElement)throw"Missing config: storeysTabElement";if(!t.showAllStoreysButtonElement)throw"Missing config: showAllStoreysButtonElement";if(!t.hideAllStoreysButtonElement)throw"Missing config: hideAllStoreysButtonElement";if(!t.storeysElement)throw"Missing config: storeysElement";if(this._storeysTabElement=t.storeysTabElement,this._showAllStoreysButtonElement=t.showAllStoreysButtonElement,this._hideAllStoreysButtonElement=t.hideAllStoreysButtonElement,this._storeysTabButtonElement=this._storeysTabElement.querySelector(".xeokit-tab-btn"),!this._storeysTabButtonElement)throw"Missing DOM element: .xeokit-tab-btn";const i=t.storeysElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,autoAddModels:!1,hierarchy:"storeys",autoExpandDepth:1}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode,pruneEmptyNodes:!0},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{const t=this.bimViewer._modelsExplorer.getModelInfo(e);t&&this._treeView.addModel(e,{rootName:t.name})}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse(),this._treeView.expandToDepth(1)})}setEnabled(e){e?(this._storeysTabButtonElement.classList.remove("disabled"),this._showAllStoreysButtonElement.classList.remove("disabled"),this._hideAllStoreysButtonElement.classList.remove("disabled")):(this._storeysTabButtonElement.classList.add("disabled"),this._showAllStoreysButtonElement.classList.add("disabled"),this._hideAllStoreysButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}selectStorey(e,t){const i=this.viewer.metaScene.metaObjects[e];if(!i)return void this.error("selectStorey() - object is not found: '"+e+"'");if("IfcBuildingStorey"!==i.type)return void this.error("selectStorey() - object is not found: '"+e+"'");const s=i.getObjectIDsInSubtree();this._selectObjects(s,t)}_selectObjects(e,t){const i=this.viewer.scene,s=i.getAABB(e);this.viewer.cameraControl.pivotPos=math.getAABB3Center(s,tempVec3$8),t?(i.setObjectsXRayed(i.objectIds,!0),i.setObjectsVisible(i.objectIds,!0),i.setObjectsPickable(i.objectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsXRayed(e,!1),i.setObjectsVisible(e,!0),i.setObjectsPickable(e,!0),this.viewer.cameraFlight.flyTo({aabb:s},()=>{setTimeout(function(){i.setObjectsVisible(i.xrayedObjectIds,!1),i.setObjectsXRayed(i.xrayedObjectIds,!1)},500),t()})):(i.setObjectsVisible(i.objectIds,!1),i.setObjectsPickable(i.xrayedObjectIds,!0),i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsVisible(e,!0),this.viewer.cameraFlight.jumpTo({aabb:s}))}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$9=math.vec3(),newLook=math.vec3(),newEye=math.vec3(),newUp=math.vec3(),newLookEyeVec=math.vec3();class CameraFlightAnimation extends Component{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=math.vec3(),this._eye1=math.vec3(),this._up1=math.vec3(),this._look2=math.vec3(),this._eye2=math.vec3(),this._up2=math.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,a,n,l,h;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)a=e.eye,n=e.look,l=e.up;else if(e.eye)a=e.eye;else if(e.look)n=e.look;else{let s=e;if((utils.isNumeric(s)||utils.isString(s))&&(h=s,!(s=this.scene.components[h])))return this.error("Component not found: "+utils.inQuotes(h)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const c=e.poi;if(o){if(o[3]=1;e>1&&(e=1);const i=this.easing?CameraFlightAnimation._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(math.subVec3(s.eye,s.look,newLookEyeVec),s.eye=math.lerpVec3(i,0,1,this._eye1,this._eye2,newEye),s.look=math.subVec3(newEye,newLookEyeVec,newLook)):this._flyingLook&&(s.look=math.lerpVec3(i,0,1,this._look1,this._look2,newLook),s.up=math.lerpVec3(i,0,1,this._up1,this._up2,newUp)):this._flyingEyeLookUp&&(s.eye=math.lerpVec3(i,0,1,this._eye1,this._eye2,newEye),s.look=math.lerpVec3(i,0,1,this._look1,this._look2,newLook),s.up=math.lerpVec3(i,0,1,this._up1,this._up2,newUp)),this._projection2){const t="ortho"===this._projection2?CameraFlightAnimation._easeOutExpo(e,0,1,1):CameraFlightAnimation._easeInCubic(e,0,1,1);s.customProjection.matrix=math.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);t?this.stop():core.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=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()}}const screenPos=math.vec4(),viewPos=math.vec4(),worldPos=math.vec4(),tempVec3a$u=math.vec3(),tempVec3b$1=math.vec3(),tempVec3c$1=math.vec3(),tempVec4a$2=math.vec4(),tempVec4b$2=math.vec4(),tempVec4c$2=math.vec4();class PanController{constructor(e){this._scene=e,this._inverseProjectMat=math.mat4(),this._transposedProjectMat=math.mat4(),this._inverseOrthoProjectMat=math.mat4(),this._transposedOrthoProjectMat=math.mat4(),this._inverseViewMat=math.mat4(),this._projMatDirty=!0,this._viewMatDirty=!0,this._sceneDiagSizeDirty=!0,this._sceneDiagSize=1,this._onCameraOrthoProjMatrix=this._scene.camera.ortho.on("matrix",()=>{this._projMatDirty=!0}),this._onCameraPerspectiveProjMatrix=this._scene.camera.perspective.on("matrix",()=>{this._projMatDirty=!0}),this._onCameraViewMatrix=this._scene.camera.on("viewMatrix",()=>{this._viewMatDirty=!0}),this._onSceneBoundary=this._scene.scene.on("boundary",()=>{this._sceneDiagSizeDirty=!0})}dolly(e,t,i){const s=this._scene.camera;if("perspective"===s.projection)s.ortho.scale=s.ortho.scale-i,this._dollyToWorldPos(e,i);else if("ortho"===s.projection){const e=this._unprojectOrtho(t,viewPos,tempVec4a$2);s.ortho.scale=s.ortho.scale-i,s.ortho._update();const r=this._unprojectOrtho(t,viewPos,tempVec4b$2),o=math.subVec3(r,e,tempVec4c$2),a=math.mulVec3Scalar(math.normalizeVec3(math.subVec3(s.look,s.eye,tempVec3a$u)),-i,tempVec3b$1),n=math.addVec3(o,a,tempVec3c$1);s.eye=[s.eye[0]-n[0],s.eye[1]-n[1],s.eye[2]-n[2]],s.look=[s.look[0]-n[0],s.look[1]-n[1],s.look[2]-n[2]]}}_getInverseProjectMat(){return this._updateProjMatrices(),this._inverseProjectMat}_getTransposedProjectMat(){return this._updateProjMatrices(),this._transposedProjectMat}_getInverseOrthoProjectMat(){return this._updateProjMatrices(),this._inverseOrthoProjectMat}_getTransposedOrthoProjectMat(){return this._updateProjMatrices(),this._transposedOrthoProjectMat}_updateProjMatrices(){this._projMatDirty&&(math.inverseMat4(this._scene.camera.perspective.matrix,this._inverseProjectMat),math.inverseMat4(this._scene.camera.ortho.matrix,this._inverseOrthoProjectMat),math.transposeMat4(this._scene.camera.perspective.matrix,this._transposedProjectMat),math.transposeMat4(this._scene.camera.ortho.matrix,this._transposedOrthoProjectMat),this._projMatDirty=!1)}_getInverseViewMat(){return this._viewMatDirty&&math.inverseMat4(this._scene.camera.viewMatrix,this._inverseViewMat),this._inverseViewMat}_getSceneDiagSize(){return this._sceneDiagSizeDirty&&(this._sceneDiagSize=math.getAABB3Diag(this._scene.aabb)),this._sceneDiagSize}_unprojectPerspective(e,t,i){const s=this._scene.canvas.canvas,r=this._getTransposedProjectMat(),o=r.subarray(8,12),a=r.subarray(12),n=[0,0,-this._getSceneDiagSize(),1],l=math.dotVec4(n,o)/math.dotVec4(n,a),h=this._getInverseProjectMat(),c=this._getInverseViewMat(),d=s.offsetWidth/2,u=s.offsetHeight/2;screenPos[0]=(e[0]-d)/d,screenPos[1]=(e[1]-u)/u,screenPos[2]=l,screenPos[3]=1,math.mulMat4v4(h,screenPos,t),math.mulVec3Scalar(t,1/t[3]),t[3]=1,t[1]*=-1,math.mulMat4v4(c,t,i)}_unprojectOrtho(e,t,i){const s=this._scene.canvas.canvas,r=this._getTransposedOrthoProjectMat(),o=r.subarray(8,12),a=r.subarray(12),n=[0,0,-this._getSceneDiagSize(),1],l=math.dotVec4(n,o)/math.dotVec4(n,a),h=this._getInverseOrthoProjectMat(),c=this._getInverseViewMat(),d=s.offsetWidth/2,u=s.offsetHeight/2;return screenPos[0]=(e[0]-d)/d,screenPos[1]=(e[1]-u)/u,screenPos[2]=l,screenPos[3]=1,math.mulMat4v4(h,screenPos,t),math.mulVec3Scalar(t,1/t[3]),t[3]=1,t[1]*=-1,math.mulMat4v4(c,t,i),i}_dollyToWorldPos(e,t){const i=this._scene.camera,s=math.subVec3(e,i.eye,tempVec3a$u);if(math.lenVec3(s){this._cameraDirty=!0}),this._onProjMatrix=this._scene.camera.on("projMatrix",()=>{this._cameraDirty=!0}),this._onTick=this._scene.on("tick",()=>{this.updatePivotElement()})}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){math.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,math.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);const o=t.canvas.getBoundingClientRect();this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-12+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-12+"px"),this._cameraDirty=!1}}setPivotElement(e){this._pivotElement=e}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=math.lookAtMat4v(e.eye,e.look,e.worldUp);math.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=math.distVec3(e.eye,i),t=math.inverseMat4(t);const s=math.transformVec3(t,this._cameraOffset),r=math.vec3();if(math.subVec3(e.eye,i,r),math.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=math.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=math.normalizeVec3(math.subVec3(e.look,e.eye,tempVec3a$v)),i=math.cross3Vec3(t,e.worldUp,tempVec3b$2);return math.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}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,this._polar+=.01*r,this._polar=math.clamp(this._polar,.001,Math.PI-.001);const o=[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=o[1];o[1]=o[2],o[2]=e}const a=math.lenVec3(math.subVec3(i.look,i.eye,math.vec3())),n=this.getPivotPos();math.addVec3(o,n);let l=math.lookAtMat4v(o,n,i.worldUp);l=math.inverseMat4(l);const h=math.transformVec3(l,this._cameraOffset);l[12]-=h[0],l[13]-=h[1],l[14]-=h[2];const c=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],math.subVec3(i.eye,math.mulVec3Scalar(c,a),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible",this._shown=!0,this._hideTimeout=window.setTimeout(()=>{this.hidePivot()},1e3)))}hidePivot(){this._shown&&(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class PickController{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.pickCursorPos=math.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;this.picked=!1,this.pickedSurface=!1,this._needFireEvents=!1;const e=this._cameraControl.hasSubs("hoverSurface");if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const t=this.pickResult.canvasPos;if(t[0]===this.pickCursorPos[0]&&t[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}if(this.schedulePickEntity&&this.pickResult){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!0,canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(this._needFireEvents){if(this.picked&&this.pickResult&&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=!1}}destroy(){this._scene.off(this._onTick)}}const canvasPos=math.vec2(),getCanvasPosFromEvent=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 MousePanRotateDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let a,n,l=0,h=0,c=0,d=0;this._down=!1;let u=!1;const p=math.vec3();let m=!0;const _=this._scene.canvas.canvas,f=[];document.addEventListener("keydown",this._documentKeyDownHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;f[r]=!0})),document.addEventListener("keyup",this._documentKeyUpHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;f[r]=!1})),_.addEventListener("mousedown",this._mouseDownHandler=(t=>{if(i.active&&i.pointerEnabled)switch(this._down=!0,t.which){case 1:f[e.input.KEY_SHIFT]||i.planView?(_.style.cursor="move",l=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult?(u=!0,p.set(o.pickResult.worldPos)):u=!1):(_.style.cursor="move",l=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1]);break;case 2:a=!0,i.panRightClick||(_.style.cursor="move",l=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1]);break;case 3:n=!0,i.panRightClick&&(_.style.cursor="move",l=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult?(u=!0,p.set(o.pickResult.worldPos)):u=!1)}})),_.addEventListener("mousemove",this._mouseMoveHandler=(t=>{if(!i.active||!i.pointerEnabled)return;if(!s.mouseover)return;if(r.inputFromMouse=!0,m=!0,!this._down)return;const o=e.canvas.boundary,c=o[2]-o[0],d=o[3]-o[1],_=s.pointerCanvasPos[0],g=s.pointerCanvasPos[1];if(f[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&n){const t=_-l,i=g-h,s=e.camera;if("perspective"===s.projection){const o=Math.abs(u?math.lenVec3(math.subVec3(p,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/d,r.panDeltaY+=1.5*i*o/d}else r.panDeltaX+=.5*s.ortho.scale*(t/d),r.panDeltaY+=.5*s.ortho.scale*(i/d)}else i.planView||(i.firstPerson?(r.rotateDeltaY-=(_-l)/c*i.dragRotationRate/2,r.rotateDeltaX+=(g-h)/d*(i.dragRotationRate/4)):(r.rotateDeltaY-=(_-l)/c*i.dragRotationRate,r.rotateDeltaX+=(g-h)/d*i.dragRotationRate));l=_,h=g})),document.addEventListener("mouseup",this._documentMouseUpHandler=(e=>{if(i.active&&i.pointerEnabled){switch(e.which){case 1:break;case 2:a=!1;break;case 3:n=!1}this._down=!1}})),_.addEventListener("mouseup",this._mouseUpHandler=(e=>{if(i.active&&i.pointerEnabled){switch(e.which){case 3:getCanvasPosFromEvent(e,canvasPos);const i=canvasPos[0],s=canvasPos[1];Math.abs(i-c)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{canvasPos:canvasPos,event:e},!0)}_.style.removeProperty("cursor")}})),_.addEventListener("mouseenter",this._mouseEnterHandler=(()=>{i.active&&i.pointerEnabled&&(this._down=!1)})),_.addEventListener("mouseleave",this._mouseLeaveHandler=(()=>{i.active&&i.pointerEnabled&&(r.panDeltaX=0,r.panDeltaY=0,r.rotateDeltaX=0,r.rotateDeltaY=0,this._down=!1)}));let g=null;_.addEventListener("wheel",this._mouseWheelHandler=(e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==g?t-g:0;g=t,o>.05&&(o=.05),o<1/60&&(o=1/60);const a=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===a)return;const n=a/Math.abs(a);r.dollyDelta+=-n*o*i.mouseWheelDollyRate,m&&(s.followPointerDirty=!0,m=!1),e.preventDefault()}))}reset(){this._down=!1}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mousemove",this._mouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const center=math.vec3(),tempVec3a$w=math.vec3(),tempVec3b$3=math.vec3(),tempVec3c$2=math.vec3(),tempVec3d$1=math.vec3(),tempCameraTarget={eye:math.vec3(),look:math.vec3(),up:math.vec3()};class KeyboardAxisViewHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.cameraControl,a=e.camera;e.input.on("keydown",this._documentKeyDownHandler=(r=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=o._isKeyDownForAction(o.AXIS_VIEW_RIGHT),l=o._isKeyDownForAction(o.AXIS_VIEW_BACK),h=o._isKeyDownForAction(o.AXIS_VIEW_LEFT),c=o._isKeyDownForAction(o.AXIS_VIEW_FRONT),d=o._isKeyDownForAction(o.AXIS_VIEW_TOP),u=o._isKeyDownForAction(o.AXIS_VIEW_BOTTOM);if(!(n||l||h||c||d||u))return;const p=e.aabb,m=math.getAABB3Diag(p);math.getAABB3Center(p,center);const _=Math.abs(m/Math.tan(t.cameraFlight.fitFOV*math.DEGTORAD)),f=1.1*m;tempCameraTarget.orthoScale=f,n?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldRight,_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp)):l?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldForward,_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp)):h?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldRight,-_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp)):c?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldForward,-_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp)):d?(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldUp,_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(math.normalizeVec3(math.mulVec3Scalar(a.worldForward,1,tempVec3b$3),tempVec3c$2))):u&&(tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldUp,-_,tempVec3a$w),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(math.normalizeVec3(math.mulVec3Scalar(a.worldForward,-1,tempVec3b$3)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(center),t.cameraFlight.duration>0?t.cameraFlight.flyTo(tempCameraTarget,()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()}):(t.cameraFlight.jumpTo(tempCameraTarget),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){document.removeEventListener("keydown",this._documentKeyDownHandler)}}class MousePickHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,h=!1;const c=this._scene.canvas.canvas,d=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;math.subVec3(i.eye,i.look,[]);t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};c.addEventListener("mousemove",this._canvasMouseMoveHandler=(t=>{if(!i.active||!i.pointerEnabled)return;if(l||h)return;const r=n.hasSubs("hover"),a=n.hasSubs("hoverOut"),c=n.hasSubs("hoverOff"),d=n.hasSubs("hoverSurface");if(r||a||c||d)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&n.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),n.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t),n.fire("hover",o.pickResult,!0),o.pickResult.worldPos&&n.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(n.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),n.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)})),c.addEventListener("mousedown",this._canvasMouseDownHandler=(t=>{1===t.which&&(l=!0),3===t.which&&(h=!0),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&&(o.pickResult?(a.setPivotPos(o.pickResult.worldPos),a.startPivot()):(a.setPivotPos(e.camera.look),a.startPivot()))))})),document.addEventListener("mouseup",this._documentMouseUpHandler=(e=>{1===e.which&&(l=!1),3===e.which&&(h=!1)})),c.addEventListener("mouseup",this._canvasMouseUpHandler=(r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(a.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=n.hasSubs("picked"),h=n.hasSubs("pickedNothing"),c=n.hasSubs("pickedSurface"),u=n.hasSubs("doublePicked"),p=n.hasSubs("doublePickedSurface"),m=n.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||m))return(l||h||c)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(n.fire("picked",o.pickResult,!0),o.pickedSurface&&n.fire("pickedSurface",o.pickResult,!0)):n.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks)this._timeout=setTimeout(()=>{o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=c,o.update(),o.pickResult?(n.fire("picked",o.pickResult,!0),o.pickedSurface&&(n.fire("pickedSurface",o.pickResult,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(o.pickResult.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):n.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0},250);else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(n.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(d(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=math.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(n.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(d(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=math.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 KeyboardPanRotateDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=e.input,a=[],n=e.canvas.canvas;t.pickController;let l=!0;document.addEventListener("mousemove",this._documentMouseMoveHandler=(()=>{l=!0})),document.addEventListener("keydown",this._documentKeyDownHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;a[r]=!0,r===o.KEY_SHIFT&&(n.style.cursor="move")})),document.addEventListener("keyup",this._documentKeyUpHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;a[r]=!1,r===o.KEY_SHIFT&&(n.style.cursor="default")})),this._onTick=e.on("tick",n=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const h=t.cameraControl,c=n.deltaTime/1e3;if(!i.planView){const e=h._isKeyDownForAction(h.ROTATE_Y_POS,a),s=h._isKeyDownForAction(h.ROTATE_Y_NEG,a),o=h._isKeyDownForAction(h.ROTATE_X_POS,a),n=h._isKeyDownForAction(h.ROTATE_X_NEG,a),l=c*i.keyboardRotationRate;(e||s||o||n)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:n&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){const e=h._isKeyDownForAction(h.DOLLY_BACKWARDS,a),o=h._isKeyDownForAction(h.DOLLY_FORWARDS,a);if(e||o){const a=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=a:e&&(r.dollyDelta+=a),l&&(s.followPointerDirty=!0,l=!1)}}const d=h._isKeyDownForAction(h.PAN_FORWARDS,a),u=h._isKeyDownForAction(h.PAN_BACKWARDS,a),p=h._isKeyDownForAction(h.PAN_LEFT,a),m=h._isKeyDownForAction(h.PAN_RIGHT,a),_=h._isKeyDownForAction(h.PAN_UP,a),f=h._isKeyDownForAction(h.PAN_DOWN,a),g=(a[o.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(d||u||p||m||_||f)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),f?r.panDeltaY+=g:_&&(r.panDeltaY+=-g),m?r.panDeltaX+=-g:p&&(r.panDeltaX+=g),u?r.panDeltaZ+=g:d&&(r.panDeltaZ+=-g))})}reset(){}destroy(){this._scene.off(this._onTick),document.removeEventListener("mousemove",this._documentMouseMoveHandler),document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler)}}const SCALE_DOLLY_EACH_FRAME=1,EPSILON=.001,tempVec3$a=math.vec3();class CameraUpdater{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,a=t.pickController,n=t.pivotController,l=t.panController;let h=SCALE_DOLLY_EACH_FRAME,c=1;this._onTick=e.on("tick",t=>{if(!i.active||!i.pointerEnabled)return;let d="default";if(Math.abs(r.dollyDelta){s.mouseover=!0})),o.addEventListener("mouseleave",this._mouseLeaveHandler=(()=>{s.mouseover=!1,o.style.cursor="default"})),o.addEventListener("mousemove",this._mouseMoveHandler=(e=>{getCanvasPosFromEvent$1(e,s.pointerCanvasPos)})),o.addEventListener("mousedown",this._mouseDownHandler=(e=>{i.active&&i.pointerEnabled&&(getCanvasPosFromEvent$1(e,s.pointerCanvasPos),s.mouseover=!0)})),o.addEventListener("mouseup",this._mouseUpHandler=(e=>{i.active&&i.pointerEnabled}))}reset(){}destroy(){const e=this._scene.canvas.canvas;e.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 getCanvasPosFromEvent$1(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 TouchPanRotateAndDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=math.vec2();let l=-1;const h=[];let c=0;const d=math.vec2(),u=(math.vec2(),this._scene.canvas.canvas);let p=!1;this._onTick=e.on("tick",()=>{p=!1}),u.addEventListener("touchstart",this._canvasTouchStartHandler=(e=>{if(!i.active||!i.pointerEnabled)return;const t=e.touches,r=e.changedTouches;if(s.touchStartTime=Date.now(),1===t.length&&1===r.length?(l=s.touchStartTime,n[0]=t[0].pageX,n[1]=t[0].pageY,i.followPointer&&(o.pickCursorPos=n,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(a.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&a.startPivot()&&a.showPivot()):!i.firstPerson&&a.startPivot()&&a.showPivot()))):l=-1,2===t.length){const e=t[0],i=t[1],s=math.geometricMeanVec2([e.pageX,e.pageY],[i.pageX,i.pageY]);o.pickCursorPos=s,o.schedulePickSurface=!0,o.update()}for(;h.length{if(!i.active||!i.pointerEnabled)return;if(p)return;p=!0;const a=e.canvas.boundary,n=a[2]-a[0],l=a[3]-a[1],u=t.touches;if(t.touches.length===c){if(1===c){const t=u[0];if(i.planView){math.subVec2([t.pageX,t.pageY],h[0],d);const s=d[0],o=d[1],a=e.camera;if("perspective"===a.projection){const t=Math.abs(e.camera.eyeLookDist)*Math.tan(a.perspective.fov/2*Math.PI/180);r.panDeltaX+=s*t/l*i.touchPanRate,r.panDeltaY+=o*t/l*i.touchPanRate}else r.panDeltaX+=.5*a.ortho.scale*(s/l)*i.touchPanRate,r.panDeltaY+=.5*a.ortho.scale*(o/l)*i.touchPanRate}else r.rotateDeltaY-=(t.pageX-h[0][0])/n*i.dragRotationRate/2,r.rotateDeltaX+=(t.pageY-h[0][1])/l*(i.dragRotationRate/4)}else if(2===c){const t=u[0],a=u[1],n=math.geometricMeanVec2(h[0],h[1]),c=math.geometricMeanVec2([t.pageX,t.pageY],[a.pageX,a.pageY]),d=math.vec2();math.subVec2(n,c,d);const p=d[0],m=d[1],_=e.camera;if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(math.lenVec3(math.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=p*s/l*i.touchPanRate,r.panDeltaY-=m*s/l*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(p/l)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/l)*i.touchPanRate;const f=math.distVec2([t.pageX,t.pageY],[a.pageX,a.pageY]),g=math.distVec2(h[0],h[1]);r.dollyDelta=(g-f)*i.touchDollyRate,s.pointerCanvasPos=c}for(let e=0;e{e.preventDefault()}),this._configs={tapInterval:150,doubleTapInterval:325,tapDistanceThreshold:4,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!1,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.05,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.06},this._states={pointerCanvasPos:math.vec2(),mouseover:!1,inputFromMouse:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:math.vec2(),tapStartTime:-1,lastTapTime:-1},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new PickController(this,this._configs),pivotController:new PivotController(i),panController:new PanController(this.scene),cameraFlight:new CameraFlightAnimation(this,{duration:.5})},this._handlers=[new MouseMiscHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new TouchPanRotateAndDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new MousePanRotateDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new KeyboardAxisViewHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new MousePickHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new KeyboardPanRotateDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new CameraUpdater(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",utils.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];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]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e{delete i[e.id];const t=s[e.type];t&&t[e.id]&&(delete t[e.id],0==--this._typeCounts[e.type]&&(delete this._typeCounts[e.type],delete s[e.type]));const o=e.children;if(o)for(let e=0,t=o.length;e0?arrayToMap(t):null,a=i&&i.length>0?arrayToMap(i):null;return function e(t){if(!t)return;var i=!0;a&&a[t.type]?i=!1:o&&!o[t.type]&&(i=!1),i&&s.push(t.id);const r=t.children;if(r)for(var n=0,l=r.length;nd.has(e.id)||p.has(e.id)||u.has(e.id)).reduce((e,i)=>{let s,r=colorizeToRGB(i.colorize);return i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,r=(s=Math.round(255*s).toString(16).padStart(2,"0"))+r):d.has(i.id)&&(r=(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"))+r),e[r]||(e[r]=[]),e[r].push({ifc_guid:i.id,originating_system:this.originatingSystem}),e},{}),_=Object.entries(m).map(([e,t])=>({color:e,components:t}));o.components.coloring=_;const f=t.objectIds,g=t.visibleObjects,v=t.visibleObjectIds,b=f.filter(e=>!g[e]),y=t.selectedObjectIds;return e.defaultInvisible||v.lengththis._objectIdToComponent(e)),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=b.map(e=>this._objectIdToComponent(e)),o.components.visibility.default_visibility=!0),o.components.selection=y.map(e=>this._objectIdToComponent(e)),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_objectIdToComponent(e){return{ifc_guid:e,originating_system:this.originatingSystem,authoring_tool_id:this.authoringTool}}setViewpoint(e,t={}){if(!e)return;const i=this.viewer,s=i.scene,r=s.camera,o=!1!==t.rayCast,a=!1!==t.immediate,n=!1!==t.reset,l=!!t.updateCompositeObjects,h=s.realWorldOffset,c=!0===t.reverseClippingPlanes;if(s.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.forEach(function(e){let t=xyzObjectToArray(e.location,tempVec3$b),i=xyzObjectToArray(e.direction,tempVec3$b);c&&math.negateVec3(i),math.subVec3(t,h),r.yUp&&(t=ZToY(t),i=ZToY(i)),new SectionPlane(s,{pos:t,dir:i})}),n&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach(e=>{const t=i.scene.objects[e.ifc_guid];t?t.visible=!1:s.setObjectsVisible(l?i.metaScene.getObjectIDsInSubtree(e.ifc_guid):e.ifc_guid,!1)})):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach(e=>{const t=i.scene.objects[e.ifc_guid];t?t.visible=!0:s.setObjectsVisible(l?i.metaScene.getObjectIDsInSubtree(e.ifc_guid):e.ifc_guid,!0)}));const t=e.components.visibility.view_setup_hints;t&&(!1===t.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===t.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!1),t.space_boundaries_visible)}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),Object.keys(s.models).forEach(()=>{e.components.selection.forEach(e=>s.setObjectsSelected(l?i.metaScene.getObjectIDsInSubtree(e.ifc_guid):e.ifc_guid,!0))})),e.components.coloring&&e.components.coloring.forEach(e=>{let t=e.components.map(e=>e.ifc_guid),i=e.color;if(8===i.length){let e=parseInt(i.substring(0,2),16)/256;i=i.substring(2),s.setObjectsOpacity(t,e)}let r=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];s.setObjectsColorized(t,r)})}if(e.perspective_camera||e.orthogonal_camera){let n,l,c,d;if(e.perspective_camera?(n=xyzObjectToArray(e.perspective_camera.camera_view_point,tempVec3$b),l=xyzObjectToArray(e.perspective_camera.camera_direction,tempVec3$b),c=xyzObjectToArray(e.perspective_camera.camera_up_vector,tempVec3$b),r.perspective.fov=e.perspective_camera.field_of_view,d="perspective"):(n=xyzObjectToArray(e.orthogonal_camera.camera_view_point,tempVec3$b),l=xyzObjectToArray(e.orthogonal_camera.camera_direction,tempVec3$b),c=xyzObjectToArray(e.orthogonal_camera.camera_up_vector,tempVec3$b),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,d="ortho"),math.subVec3(n,h),r.yUp&&(n=ZToY(n),l=ZToY(l),c=ZToY(c)),o){const e=s.pick({pickSurface:!0,origin:n,direction:l});l=e?e.worldPos:math.addVec3(n,l,tempVec3$b)}else l=math.addVec3(n,l,tempVec3$b);a?(r.eye=n,r.look=l,r.up=c,r.projection=d):i.cameraFlight.flyTo({eye:n,look:l,up:c,duration:t.duration,projection:d})}}destroy(){super.destroy()}}function xyzArrayToObject(e){return{x:e[0],y:e[1],z:e[2]}}function xyzObjectToArray(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function YToZ(e){return new Float64Array([e[0],-e[2],e[1]])}function ZToY(e){return new Float64Array([e[0],e[2],-e[1]])}function colorizeToRGB(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0")}const tempVec3a$x=math.vec3();class ThreeDMode extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";this._buttonElement=t.buttonElement,this._cameraControlNavModeMediator=t.cameraControlNavModeMediator,this._active=!1,this.on("enabled",e=>{e?this._buttonElement.classList.remove("disabled"):this._buttonElement.classList.add("disabled")}),this._buttonElement.addEventListener("click",e=>{this.setActive(!this.getActive(),()=>{}),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!0,()=>{})})}setActive(e,t){this._active!==e?(this._active=e,e?(this._buttonElement.classList.add("active"),t?this._enterThreeDMode(()=>{this.fire("active",this._active),t()}):(this._enterThreeDMode(),this.fire("active",this._active))):(this._buttonElement.classList.remove("active"),t?this._exitThreeDMode(()=>{this.fire("active",this._active),t()}):(this._exitThreeDMode(),this.fire("active",this._active)))):t&&t()}_enterThreeDMode(e){const t=this.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds),r=math.getAABB3Diag(s),o=math.getAABB3Center(s,tempVec3a$x),a=Math.abs(r/Math.tan(32.5)),n=i.camera,l=n.yUp?[-1,-1,-1]:[1,1,1],h=n.yUp?[-1,1,-1]:[-1,1,1];t.cameraControl.pivotPos=o,this.bimViewer._navCubeMode.setActive(!0),this.bimViewer._firstPersonMode.setEnabled(!0),this._cameraControlNavModeMediator.setThreeDModeActive(!0),this.bimViewer._sectionTool.setEnabled(!0),e?t.cameraFlight.flyTo({look:o,eye:[o[0]-a*l[0],o[1]-a*l[1],o[2]-a*l[2]],up:h,orthoScale:1.3*r,duration:1},()=>{e()}):t.cameraFlight.jumpTo({look:o,eye:[o[0]-a*l[0],o[1]-a*l[1],o[2]-a*l[2]],up:h,orthoScale:1.3*r})}_exitThreeDMode(e){const t=this.viewer,i=t.scene,s=i.camera,r=i.getAABB(i.visibleObjectIds),o=math.getAABB3Center(r),a=math.getAABB3Diag(r),n=Math.abs(a/Math.tan(45*math.DEGTORAD)),l=1.3*a,h=tempVec3a$x;h[0]=o[0]+s.worldUp[0]*n,h[1]=o[1]+s.worldUp[1]*n,h[2]=o[2]+s.worldUp[2]*n;const c=math.mulVec3Scalar(s.worldForward,-1,[]);this.bimViewer._sectionTool.setActive(!1),this.bimViewer._sectionTool.clear(),this.bimViewer._firstPersonMode.setEnabled(!1),this.bimViewer._sectionTool.setEnabled(!1),this._cameraControlNavModeMediator.setThreeDModeActive(!1),e?t.cameraFlight.flyTo({eye:h,look:o,up:c,orthoScale:l},()=>{this.bimViewer._navCubeMode.setActive(!1)}):(t.cameraFlight.jumpTo({eye:h,look:o,up:c,orthoScale:l}),this.bimViewer._navCubeMode.setActive(!1))}}class ObjectContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"View Fit",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity;t.cameraFlight.flyTo({aabb:s.aabb,duration:.5},()=>{setTimeout(function(){i.setObjectsHighlighted(i.highlightedObjectIds,!1)},500)}),t.cameraControl.pivotPos=math.getAABB3Center(s.aabb)}},{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}},{title:"Show in Tree",doAction:function(e){const t=e.entity.id;e.showObjectInExplorers(t)}}],[{title:"Hide",getEnabled:function(e){return e.entity.visible},doAction:function(e){e.entity.visible=!1}},{title:"Hide Others",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity,r=t.metaScene.metaObjects[s.id];r&&(i.setObjectsVisible(i.visibleObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),r.withMetaObjectsInSubtree(e=>{const t=i.objects[e.id];t&&(t.visible=!0)}))}},{title:"Hide All",getEnabled:function(e){return e.viewer.scene.numVisibleObjects>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}},{title:"Show All",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray",getEnabled:function(e){return!e.entity.xrayed},doAction:function(e){const t=e.entity;t.xrayed=!0,t.pickable=!1}},{title:"X-Ray Others",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity,r=t.metaScene.metaObjects[s.id];r&&(i.setObjectsVisible(i.objectIds,!0),i.setObjectsXRayed(i.objectIds,!0),i.setObjectsPickable(i.objectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),r.withMetaObjectsInSubtree(e=>{const t=i.objects[e.id];t&&(t.xrayed=!1,t.pickable=!0)}))}},{title:"X-Ray All",getEnabled:function(e){const t=e.viewer.scene;return t.numXRayedObjects0},doAction:function(e){const t=e.viewer.scene,i=t.xrayedObjectIds;t.setObjectsPickable(i,!0),t.setObjectsXRayed(i,!1)}}],[{title:"Select",getEnabled:function(e){return!e.entity.selected},doAction:function(e){e.entity.selected=!0}},{title:"Undo Select",getEnabled:function(e){return e.entity.selected},doAction:function(e){e.entity.selected=!1}},{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class CanvasContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"Hide All",getEnabled:function(e){return e.viewer.scene.numVisibleObjects>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}},{title:"Show all",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}}],[{title:"X-Ray All",getEnabled:function(e){const t=e.viewer.scene;return t.numXRayedObjects0},doAction:function(e){const t=e.viewer.scene.xrayedObjectIds;e.viewer.scene.setObjectsPickable(t,!0),e.viewer.scene.setObjectsXRayed(t,!1)}}],[{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Reset View",doAction:function(e){e.bimViewer.resetView()}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class OrthoMode extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";this._buttonElement=t.buttonElement,this.on("enabled",e=>{e?this._buttonElement.classList.remove("disabled"):this._buttonElement.classList.add("disabled")}),this._buttonElement.addEventListener("click",e=>{this.setActive(!this.getActive()),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)})}setActive(e,t){this._active!==e?(this._active=e,e?(this._buttonElement.classList.add("active"),t?this._enterOrthoMode(()=>{this.fire("active",this._active),t()}):(this._enterOrthoMode(),this.fire("active",this._active))):(this._buttonElement.classList.remove("active"),t?this._exitOrthoMode(()=>{this.fire("active",this._active),t()}):(this._exitOrthoMode(),this.fire("active",this._active)))):t&&t()}_enterOrthoMode(e){this.viewer.cameraFlight.flyTo({projection:"ortho",duration:.5},e)}_exitOrthoMode(e){this.viewer.cameraFlight.flyTo({projection:"perspective",duration:.5},e)}}function createExplorerTemplate(e){return'
\n
\n Models\n
\n
\n \n '+(e.enableEditModels?'':"")+'
\n
\n
\n
\n
\n Objects\n
\n
\n \n \n
\n
\n
\n
\n
\n Classes\n
\n
\n \n \n
\n
\n
\n
\n
\n Storeys\n
\n
\n \n \n
\n
\n
\n
\n
'}const toolbarTemplate='
\n \x3c!-- Reset button --\x3e\n
\n \n
\n
\n \x3c!-- 3D Mode button --\x3e\n \n \x3c!-- Perspective/Ortho Mode button --\x3e\n \n \x3c!-- Fit button --\x3e\n \n \x3c!-- First Person mode button --\x3e\n \n
\n \x3c!-- Tools button group --\x3e\n
\n \x3c!-- Hide tool button --\x3e\n \n \x3c!-- Select tool button --\x3e\n \n \x3c!-- Query tool button --\x3e\n \n \x3c!-- section tool button --\x3e\n \n
\n\n
';function initTabs(e){const t="xeokit-tab",i="active";function s(e){let s=e.parentNode.querySelectorAll("."+t);for(let t=0;t{e.preventDefault()}),r.oncontextmenu=(e=>{e.preventDefault()}),o.oncontextmenu=(e=>{e.preventDefault()});const l=new Viewer({canvasElement:i,transparent:!0});super(null,t,e,l),this._configs={},this.viewer=l,this._customizeViewer(),this._initCanvasContextMenus(),this._initConfigs(),this._enableAddModels=!!t.enableEditModels,s.innerHTML=createExplorerTemplate(t),r.innerHTML=toolbarTemplate,this._explorerElement=s,initTabs(s),this._modelsExplorer=new ModelsExplorer(this,{modelsTabElement:s.querySelector(".xeokit-modelsTab"),loadModelsButtonElement:s.querySelector(".xeokit-loadAllModels"),unloadModelsButtonElement:s.querySelector(".xeokit-unloadAllModels"),addModelButtonElement:s.querySelector(".xeokit-addModel"),modelsElement:s.querySelector(".xeokit-models"),enableEditModels:this._enableAddModels}),this._objectsExplorer=new ObjectsExplorer(this,{objectsTabElement:s.querySelector(".xeokit-objectsTab"),showAllObjectsButtonElement:s.querySelector(".xeokit-showAllObjects"),hideAllObjectsButtonElement:s.querySelector(".xeokit-hideAllObjects"),objectsElement:s.querySelector(".xeokit-objects")}),this._classesExplorer=new ClassesExplorer(this,{classesTabElement:s.querySelector(".xeokit-classesTab"),showAllClassesButtonElement:s.querySelector(".xeokit-showAllClasses"),hideAllClassesButtonElement:s.querySelector(".xeokit-hideAllClasses"),classesElement:s.querySelector(".xeokit-classes")}),this._storeysExplorer=new StoreysExplorer(this,{storeysTabElement:s.querySelector(".xeokit-storeysTab"),showAllStoreysButtonElement:s.querySelector(".xeokit-showAllStoreys"),hideAllStoreysButtonElement:s.querySelector(".xeokit-hideAllStoreys"),storeysElement:s.querySelector(".xeokit-storeys")}),this._resetAction=new ResetAction(this,{buttonElement:r.querySelector(".xeokit-reset"),active:!1}),this._fitAction=new FitAction(this,{buttonElement:r.querySelector(".xeokit-fit"),active:!1});const h=new function(e){let t=!1;this.setThreeDModeActive=(i=>{i?(e._firstPersonMode.setActive(!1),e.viewer.cameraControl.navMode="orbit"):(e._firstPersonMode.setActive(!1),e.viewer.cameraControl.navMode="planView"),t=i}),this.setFirstPersonModeActive=(i=>{e.viewer.cameraControl.navMode=i?"firstPerson":t?"orbit":"planView"})}(this);this._threeDMode=new ThreeDMode(this,{buttonElement:r.querySelector(".xeokit-threeD"),cameraControlNavModeMediator:h,active:!1}),this._orthoMode=new OrthoMode(this,{buttonElement:r.querySelector(".xeokit-ortho"),active:!1}),this._firstPersonMode=new FirstPersonMode(this,{buttonElement:r.querySelector(".xeokit-firstPerson"),cameraControlNavModeMediator:h,active:!1}),this._hideTool=new HideTool(this,{buttonElement:r.querySelector(".xeokit-hide"),active:!1}),this._selectionTool=new SelectionTool(this,{buttonElement:r.querySelector(".xeokit-select"),active:!1}),this._queryTool=new QueryTool(this,{buttonElement:r.querySelector(".xeokit-query"),queryInfoPanelElement:a,active:!1}),this._sectionTool=new SectionTool(this,{buttonElement:r.querySelector(".xeokit-section"),counterElement:r.querySelector(".xeokit-section-counter"),menuButtonElement:r.querySelector(".xeokit-section-menu-button"),menuButtonArrowElement:r.querySelector(".xeokit-section-menu-button-arrow"),active:!1}),this._navCubeMode=new NavCubeMode(this,{navCubeCanvasElement:o,active:!0}),this._busyModal=new BusyModal(this,{busyModalBackdropElement:n}),this._threeDMode.setActive(!0),this._firstPersonMode.setActive(!1),this._navCubeMode.setActive(!0),this._modelsExplorer.on("modelLoaded",e=>{this._modelsExplorer.getNumModelsLoaded()>0&&this.setControlsEnabled(!0),this.fire("modelLoaded",e)}),this._modelsExplorer.on("modelUnloaded",e=>{0===this._modelsExplorer.getNumModelsLoaded()&&(this.setControlsEnabled(!1),this.openTab("models")),this.fire("modelUnloaded",e)}),this._queryTool.on("queryPicked",e=>{this.fire("queryPicked",e)}),this._queryTool.on("queryNotPicked",()=>{this.fire("queryNotPicked",!0)}),this._resetAction.on("reset",()=>{this.fire("reset",!0)}),this._mutexActivation([this._queryTool,this._hideTool,this._selectionTool,this._sectionTool]),s.querySelector(".xeokit-showAllObjects").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllObjects").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-showAllClasses").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllClasses").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-showAllStoreys").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllStoreys").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-loadAllModels").addEventListener("click",e=>{this.setControlsEnabled(!1),this.loadAllModels(),e.preventDefault()}),s.querySelector(".xeokit-unloadAllModels").addEventListener("click",e=>{this.setControlsEnabled(!1),this._modelsExplorer.unloadAllModels(),e.preventDefault()}),this._enableAddModels&&s.querySelector(".xeokit-addModel").addEventListener("click",e=>{this.fire("addModel",{}),e.preventDefault()}),this._bcfViewpointsPlugin=new BCFViewpointsPlugin(this.viewer,{})}_customizeViewer(){const e=this.viewer.scene;e.xrayMaterial.fill=!1,e.xrayMaterial.fillAlpha=.1,e.xrayMaterial.fillColor=[0,0,0],e.xrayMaterial.edges=!0,e.xrayMaterial.edgeAlpha=.3,e.xrayMaterial.edgeColor=[0,0,0],e.highlightMaterial.edges=!0,e.highlightMaterial.edgeColor=[.5,.5,0],e.highlightMaterial.edgeAlpha=.9,e.highlightMaterial.fill=!0,e.highlightMaterial.fillAlpha=.1,e.highlightMaterial.fillColor=[1,0,0],e.clearLights(),new AmbientLight(e,{color:[.3,.3,.3],intensity:1}),new DirLight(e,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"world"}),new DirLight(e,{dir:[-.8,-.4,.4],color:[1,1,1],intensity:1,space:"world"}),new DirLight(e,{dir:[.2,-.8,.8],color:[.6,.6,.6],intensity:1,space:"world"}),this.viewer.cameraControl.panRightClick=!0,this.viewer.cameraControl.followPointer=!0,this.viewer.cameraControl.doublePickFlyTo=!0,this.viewer.cameraControl.keyboardDollyRate=100,this.viewer.cameraControl.mouseWheelDollyRate=100,this.viewer.cameraControl.dollyInertia=0,this.viewer.cameraControl.dollyMinSpeed=.04,this.viewer.cameraControl.dollyProximityThreshold=30;const t=document.createRange().createContextualFragment("
").firstChild;document.body.appendChild(t),this.viewer.cameraControl.pivotElement=t,e.camera.perspective.near=.01,e.camera.perspective.far=3e3,e.camera.ortho.near=.01,e.camera.ortho.far=3e3;const i=e.sao;i.enabled=!1,i.bias=.5,i.intensity=.2,i.scale=1200,i.kernelRadius=100;var s=200,r=!1;e.camera.on("matrix",()=>{if(this._configs.saoInteractive)return;const t=this._configs.saoInteractiveDelay;s=null!==t&&void 0!==t?this._configs.saoInteractiveDelay:200,r&&(e.sao.enabled=!1,r=!1)}),e.on("tick",t=>{this._configs.saoInteractive?r||(e.sao.enabled=!!this._configs.saoEnabled,r=!0):r||(s-=t.deltaTime)<=0&&(r||(e.sao.enabled=!!this._configs.saoEnabled,r=!0))})}_initCanvasContextMenus(){this._canvasContextMenu=new CanvasContextMenu,this._objectContextMenu=new ObjectContextMenu,this.viewer.cameraControl.on("rightClick",e=>{const t=e.event,i=this.viewer.scene.pick({canvasPos:[t.offsetX,t.offsetY]});i&&i.entity.isObject?(this._canvasContextMenu.hide(),this._objectContextMenu.context={viewer:this.viewer,bimViewer:this,showObjectInExplorers:e=>{const t=this.getOpenTab();"objects"!==t&&"classes"!==t&&"storeys"!==t&&this.openTab("objects"),this.showObjectInExplorers(e)},entity:i.entity},this._objectContextMenu.show(t.pageX,t.pageY)):(this._objectContextMenu.hide(),this._canvasContextMenu.context={viewer:this.viewer,bimViewer:this},this._canvasContextMenu.show(t.pageX,t.pageY))})}_initConfigs(){this.setConfigs({cameraNear:"0.05",cameraFar:"3000.0",saoEnabled:"false",saoBias:"0.5",saoIntensity:"0.5",saoScale:"1200.0",saoKernelRadius:"100",xrayContext:!0,backgroundColor:[1,1,1],saoInteractive:!0,saoInteractiveDelay:200,objectColorSource:"model"})}setConfigs(e){for(let t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setConfig(t,i)}}setConfig(e,t){function i(e){return!0===e||"true"===e}try{switch(e){case"backgroundColor":const r=t;this.setBackgroundColor(r),this._configs[e]=r;break;case"cameraNear":const o=parseFloat(t);this.viewer.scene.camera.perspective.near=o,this.viewer.scene.camera.ortho.near=o,this._configs[e]=o;break;case"cameraFar":const a=parseFloat(t);this.viewer.scene.camera.perspective.far=a,this.viewer.scene.camera.ortho.far=a,this._configs[e]=a;break;case"saoEnabled":this.viewer.scene.sao.enabled=this._configs[e]=i(t);break;case"saoBias":this.viewer.scene.sao.bias=parseFloat(t);break;case"saoIntensity":this.viewer.scene.sao.intensity=parseFloat(t);break;case"saoScale":this.viewer.scene.sao.scale=this._configs[e]=parseFloat(t);break;case"saoKernelRadius":this.viewer.scene.sao.kernelRadius=this._configs[e]=parseFloat(t);break;case"saoBlur":this.viewer.scene.sao.blur=this._configs[e]=i(t);break;case"viewFitFOV":this.viewer.cameraFlight.fitFOV=this._configs[e]=parseFloat(t);break;case"viewFitDuration":this.viewer.cameraFlight.duration=this._configs[e]=parseFloat(t);break;case"perspectiveFOV":this.viewer.camera.perspective.fov=this._configs[e]=parseFloat(t);break;case"excludeUnclassifiedObjects":this._configs[e]=i(t);break;case"objectColorSource":this.setObjectColorSource(t),this._configs[e]=t;break;case"xrayContext":this._configs[e]=t;break;case"saoInteractive":this._configs.saoInteractive=i(t);break;case"saoInteractiveDelay":var s=parseFloat(t);s<0&&(this.error("setConfig() - saoInteractiveDelay cannot be less than zero - clamping to zero"),s=0),this._configs.saoInteractiveDelay=parseFloat(t);break;default:this.error("setConfig() - unsupported configuration: '"+e+"'")}}catch(t){this.error("setConfig() - failed to configure '"+e+"': "+t)}}getConfig(e){return this._configs[e]}getProjectsInfo(e,t){e?this.server.getProjects(e,e=>{this.error("getProjectsInfo() - "+e),t&&t(e)}):this.error("getProjectsInfo() - Argument expected: 'done'")}getProjectInfo(e,t,i){e?t?this.server.getProject(e,t,e=>{this.error("getProjectInfo() - "+e),i&&i(e)}):this.error("getProjectInfo() - Argument expected: 'done'"):this.error("getProjectInfo() - Argument expected: projectId")}getObjectInfo(e,t,i,s,r){e?t?i?s?this.server.getObjectInfo(e,t,i,s,e=>{r&&r(e)}):this.error("getProjectInfo() - Argument expected: 'done'"):this.error("getObjectInfo() - Argument expected: objectId"):this.error("getObjectInfo() - Argument expected: modelId"):this.error("getObjectInfo() - Argument expected: projectId")}loadProject(e,t,i){e?this._modelsExplorer.loadProject(e,()=>{t&&t()},e=>{this.error("loadProject() - "+e),i&&i(e)}):this.error("loadProject() - Argument expected: objectId")}unloadProject(){this._modelsExplorer.unloadProject(),this.openTab("models"),this.setControlsEnabled(!1)}getLoadedProjectId(){return this._modelsExplorer.getLoadedProjectId()}getModelIds(){return this._modelsExplorer.getModelIds()}loadModel(e,t,i){e?this._modelsExplorer.loadModel(e,()=>{t&&t()},e=>{this.error("loadModel() - "+e),i&&i(e)}):this.error("loadModel() - Argument expected: modelId")}loadAllModels(e=function(){}){const t=this._modelsExplorer.getModelIds(),i=(e,s)=>{if(e>=t.length)s();else{const r=t[e];this._modelsExplorer.isModelLoaded(r)?i(e+1,s):this._modelsExplorer.loadModel(r,()=>{i(e+1,s)},t=>{this.error("loadAllModels() - "+t),i(e+1,s)})}};i(0,e)}getLoadedModelIds(){return this._modelsExplorer._getLoadedModelIds()}isModelLoaded(e){if(e)return this._modelsExplorer.isModelLoaded(e);this.error("unloadModel() - Argument expected: modelId")}unloadModel(e){e?this._modelsExplorer.unloadModel(e):this.error("unloadModel() - Argument expected: modelId")}unloadAllModels(){this._modelsExplorer.unloadAllModels()}editModel(e){this.fire("editModel",{modelId:e})}deleteModel(e){this.fire("deleteModel",{modelId:e})}addModel(){this.fire("addModel",{})}setBackgroundColor(e){this.viewer.scene.canvas.canvas.style.background="rgba("+255*e[0]+","+255*e[1]+","+255*e[2]+", 1.0)"}setObjectColorSource(e){switch(e){case"model":case"viewer":break;default:return e="model",void this.error("setObjectColorSource() - Unsupported value - accepted values are 'model' and 'viewer' - defaulting to 'model'")}this._objectColorSource=e}getObjectColorSource(){return this._objectColorSource||"model"}setViewerState(e,t=(()=>{})){e.tabOpen&&this.openTab(e.tabOpen),e.expandObjectsTree&&this._objectsExplorer.expandTreeViewToDepth(e.expandObjectsTree),e.expandClassesTree&&this._classesExplorer.expandTreeViewToDepth(e.expandClassesTree),e.expandStoreysTree&&this._storeysExplorer.expandTreeViewToDepth(e.expandStoreysTree),e.setCamera&&this.setCamera(e.setCamera),this._parseSelectedStorey(e,()=>{this._parseThreeDMode(e,()=>{t()})})}_parseSelectedStorey(e,t){e.selectedStorey?(this.selectStorey(e.selectedStorey),t()):t()}_parseThreeDMode(e,t){const i=!1!==e.threeDActive;this.set3DEnabled(i,t)}showObjectInExplorers(e){e?(this._objectsExplorer.showNodeInTreeView(e),this._classesExplorer.showNodeInTreeView(e),this._storeysExplorer.showNodeInTreeView(e)):this.error("showObjectInExplorers() - Argument expected: objectId")}unShowObjectInExplorers(){this._objectsExplorer.unShowNodeInTreeView(),this._classesExplorer.unShowNodeInTreeView(),this._storeysExplorer.unShowNodeInTreeView()}setObjectsVisible(e,t){this._withObjectsInSubtree(e,e=>{e.visible=t})}setAllObjectsVisible(e){e?this.viewer.scene.setObjectsVisible(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsVisible(this.viewer.scene.visibleObjectIds,!1)}setObjectsXRayed(e,t){this._withObjectsInSubtree(e,e=>{e.xrayed=t})}setAllObjectsXRayed(e){e?this.viewer.scene.setObjectsXRayed(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsXRayed(this.viewer.scene.xrayedObjectIds,!1)}setObjectsSelected(e,t){this._withObjectsInSubtree(e,e=>{e.selected=t})}setAllObjectsSelected(e){e?this.viewer.scene.setObjectsSelected(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsSelected(this.viewer.scene.selectedObjectIds,!1)}_withObjectsInSubtree(e,t){if(e)for(let i=0,s=e.length;i{const i=this.viewer.scene.objects[e.id];i&&t(i)})}else this.error("Argument expected: objectIds")}flyToObject(e,t){if(!e)return void this.error("flyToObject() - Argument expected: objectId");const i=this.viewer,s=i.scene,r=[];if(this.viewer.metaScene.withMetaObjectsInSubtree(e,e=>{s.objects[e.id]&&r.push(e.id)}),0===r.length)return this.error("Object not found in viewer: '"+e+"'"),void(t&&t());s.setObjectsVisible(r,!0),s.setObjectsHighlighted(r,!0);const o=s.getAABB(r);i.cameraFlight.flyTo({aabb:o},()=>{t&&t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}),i.cameraControl.pivotPos=math.getAABB3Center(o)}viewFitObjects(e,t){if(!e)return void this.error("flyToObject() - Argument expected: objectIds");const i=this.viewer,s=i.scene,r=[];for(var o=0,a=e.length;o{s.objects[e.id]&&r.push(e.id)})}if(0===r.length)return void(t&&t());s.setObjectsVisible(r,!0),s.setObjectsHighlighted(r,!0);const n=s.getAABB(r);i.cameraFlight.flyTo({aabb:n},()=>{t&&t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}),i.cameraControl.pivotPos=math.getAABB3Center(n)}viewFitAll(e){const t=this.viewer,i=t.scene.getAABB();t.cameraFlight.flyTo({aabb:i},()=>{e&&e()}),t.cameraControl.pivotPos=math.getAABB3Center(i)}jumpToObject(e){if(!e)return void this.error("jumpToObject() - Argument expected: objectId");const t=this.viewer,i=t.scene,s=[];if(this.viewer.metaScene.withMetaObjectsInSubtree(e,e=>{i.objects[e.id]&&s.push(e.id)}),0===s.length)return void this.error("Object not found in viewer: '"+e+"'");i.setObjectsVisible(s,!0);const r=i.getAABB(s);t.cameraFlight.jumpTo({aabb:r}),t.cameraControl.pivotPos=math.getAABB3Center(r)}setCamera(e){const t=this.viewer.scene.camera;e.eye&&(t.eye=e.eye),e.look&&(t.look=e.look),e.up&&(t.up=e.up)}viewFitModels(e,t){if(!e)return void this.error("viewFitModels() - Argument expected: modelIds");const i=this.viewer,s=i.scene,r=math.AABB3();math.collapseAABB3(r);for(var o=0,a=e.length;o{t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}):(i.cameraFlight.jumpTo({aabb:r}),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)),i.cameraControl.pivotPos=math.getAABB3Center(r)}openTab(e){if(!e)return void this.error("openTab() - Argument expected: tabId");let t;switch(e){case"models":t="xeokit-modelsTab";break;case"objects":t="xeokit-objectsTab";break;case"classes":t="xeokit-classesTab";break;case"storeys":t="xeokit-storeysTab";break;default:return void this.error("openTab() - tab not recognized: '"+e+"'")}let i=this._explorerElement.querySelectorAll(".xeokit-tab"),s=this._explorerElement.querySelector("."+t);for(let e=0;e-1}return e(this._explorerElement.querySelector(".xeokit-modelsTab"),"active")?"models":e(this._explorerElement.querySelector(".xeokit-objectsTab"),"active")?"objects":e(this._explorerElement.querySelector(".xeokit-classesTab"),"active")?"classes":e(this._explorerElement.querySelector(".xeokit-storeysTab"),"active")?"storeys":"none"}set3DEnabled(e,t){this._threeDMode.setActive(e,t)}get3DEnabled(){return this._threeDMode.getActive()}setOrthoEnabled(e,t){this._orthoMode.setActive(e,t)}getOrthoEnabled(){return this._orthoMode.getActive()}selectStorey(e,t){const i=this.viewer.metaScene.metaObjects[e];i?"IfcBuildingStorey"===i.type?this._storeysExplorer.selectStorey(e,t):this.error("selectStorey() - Object is not an IfcBuildingStorey: '"+e+"'"):this.error("selectStorey() - Object is not found: '"+e+"'")}saveBCFViewpoint(e){return this._bcfViewpointsPlugin.getViewpoint(e)}loadBCFViewpoint(e,t){e?this._bcfViewpointsPlugin.setViewpoint(e,t):this.error("loadBCFViewpoint() - Argument expected: bcfViewpoint")}resetView(){this._resetAction.reset()}setControlsEnabled(e){this._objectsExplorer.setEnabled(e),this._classesExplorer.setEnabled(e),this._storeysExplorer.setEnabled(e),this._resetAction.setEnabled(e),this._fitAction.setEnabled(e),this._threeDMode.setEnabled(e),this._orthoMode.setEnabled(e),this._firstPersonMode.setEnabled(e),this._queryTool.setEnabled(e),this._hideTool.setEnabled(e),this._selectionTool.setEnabled(e),this._sectionTool.setEnabled(e)}setKeyboardEnabled(e){this.viewer.scene.input.keyboardEnabled=e}getKeyboardEnabled(){return this.viewer.scene.input.keyboardEnabled}clearSections(){this._sectionTool.clear()}flipSections(){this._sectionTool.flipSections()}getNumSections(){return this._sectionTool.getNumSections()}destroy(){this.viewer.destroy(),this._bcfViewpointsPlugin.destroy(),this._canvasContextMenu.destroy(),this._objectContextMenu.destroy()}}export{BIMViewer,Server};