@xeokit/xeokit-sdk 2.4.0-alpha-37 → 2.4.0-alpha-38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class s{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class i{constructor(){this.items=[]}}class n{constructor(e,t,s,i,n){this.id=e,this.getTitle=t,this.doAction=s,this.getEnabled=i,this.getShown=n,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class r{constructor(e,t,s){this.id=s&&s.id?s.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let n;if(i)for(const s in i)i.hasOwnProperty(s)&&(n=i[s],this._eventCallDepth++,this._eventCallDepth<300?n.callback.call(n.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let n=this._eventSubs[t];n?this._eventSubsNum[t]++:(n={},this._eventSubs[t]=n,this._eventSubsNum[t]=1);const r=this._subIdMap.addItem();n[r]={callback:s,scope:i||this},this._subIdEvents[r]=t;const a=this._events[t];return void 0!==a&&s.call(i||this,a),r}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,n=this.on(e,(function(e){i.off(n),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}let a=!0,o=a?Float64Array:Float32Array;const l=new o(16),c=new o(16),u=new o(4),h={setDoublePrecisionEnabled(e){a=e,o=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,vec2:e=>new o(e||2),vec3:e=>new o(e||3),vec4:e=>new o(e||4),mat3:e=>new o(e||9),mat3ToMat4:(e,t=new o(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 o(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,s){const i=new o(2);for(let n=0,r=e.length;n<r;n++)h.splitDouble(e[n],i),t[n]=i[0],s[n]=i[1]},splitDouble(e,t){const s=o.from([e])[0],i=e-s;t[0]=s,t[1]=i},createUUID:(()=>{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&n]}${e[n>>8&255]}${e[n>>16&255]}${e[n>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,e)),fmod(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new o(e[0]);for(let s=1;s<e.length;s++)t[0]+=e[s][0],t[1]+=e[s][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],n=e[2],r=t[0],a=t[1],o=t[2];return[i*o-n*a,n*r-s*o,s*a-i*r,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],n=e[1],r=e[2],a=t[0],o=t[1],l=t[2];return s[0]=n*l-r*o,s[1]=r*a-i*l,s[2]=i*o-n*a,s},sqLenVec4:e=>h.dotVec4(e,e),lenVec4:e=>Math.sqrt(h.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>h.dotVec3(e,e),sqLenVec2:e=>h.dotVec2(e,e),lenVec3:e=>Math.sqrt(h.sqLenVec3(e)),distVec3:(()=>{const e=new o(3);return(t,s)=>h.lenVec3(h.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(h.sqLenVec2(e)),distVec2:(()=>{const e=new o(2);return(t,s)=>h.lenVec2(h.subVec2(t,s,e))})(),rcpVec3:(e,t)=>h.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/h.lenVec4(e);return h.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/h.lenVec3(e);return h.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/h.lenVec2(e);return h.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=h.dotVec3(e,t)/Math.sqrt(h.sqLenVec3(e)*h.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new o(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=h.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=h.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=h.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s<i;s++)t[s]=e(t[s]);return t}})(),xyzArrayToObject:e=>({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||h.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>h.m4s(0),setMat4ToOnes:()=>h.m4s(1),diagonalMat4v:e=>new o([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,s,i)=>h.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>h.diagonalMat4c(e,e,e,e),identityMat4:(e=new o(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 o(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>h.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],n=e[1],r=e[2],a=e[3],o=e[4],l=e[5],c=e[6],u=e[7],h=e[8],p=e[9],d=e[10],A=e[11],f=e[12],I=e[13],m=e[14],y=e[15],v=t[0],w=t[1],g=t[2],T=t[3],E=t[4],b=t[5],_=t[6],D=t[7],P=t[8],C=t[9],R=t[10],B=t[11],x=t[12],S=t[13],O=t[14],N=t[15];return s[0]=v*i+w*o+g*h+T*f,s[1]=v*n+w*l+g*p+T*I,s[2]=v*r+w*c+g*d+T*m,s[3]=v*a+w*u+g*A+T*y,s[4]=E*i+b*o+_*h+D*f,s[5]=E*n+b*l+_*p+D*I,s[6]=E*r+b*c+_*d+D*m,s[7]=E*a+b*u+_*A+D*y,s[8]=P*i+C*o+R*h+B*f,s[9]=P*n+C*l+R*p+B*I,s[10]=P*r+C*c+R*d+B*m,s[11]=P*a+C*u+R*A+B*y,s[12]=x*i+S*o+O*h+N*f,s[13]=x*n+S*l+O*p+N*I,s[14]=x*r+S*c+O*d+N*m,s[15]=x*a+S*u+O*A+N*y,s},mulMat3(e,t,s){s||(s=new o(9));const i=e[0],n=e[3],r=e[6],a=e[1],l=e[4],c=e[7],u=e[2],h=e[5],p=e[8],d=t[0],A=t[3],f=t[6],I=t[1],m=t[4],y=t[7],v=t[2],w=t[5],g=t[8];return s[0]=i*d+n*I+r*v,s[3]=i*A+n*m+r*w,s[6]=i*f+n*y+r*g,s[1]=a*d+l*I+c*v,s[4]=a*A+l*m+c*w,s[7]=a*f+l*y+c*g,s[2]=u*d+h*I+p*v,s[5]=u*A+h*m+p*w,s[8]=u*f+h*y+p*g,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=h.vec4()){const i=t[0],n=t[1],r=t[2],a=t[3];return s[0]=e[0]*i+e[4]*n+e[8]*r+e[12]*a,s[1]=e[1]*i+e[5]*n+e[9]*r+e[13]*a,s[2]=e[2]*i+e[6]*n+e[10]*r+e[14]*a,s[3]=e[3]*i+e[7]*n+e[11]*r+e[15]*a,s},transposeMat4(e,t){const s=e[4],i=e[14],n=e[8],r=e[13],a=e[12],o=e[9];if(!t||e===t){const t=e[1],l=e[2],c=e[3],u=e[6],h=e[7],p=e[11];return e[1]=s,e[2]=n,e[3]=a,e[4]=t,e[6]=o,e[7]=r,e[8]=l,e[9]=u,e[11]=i,e[12]=c,e[13]=h,e[14]=p,e}return t[0]=e[0],t[1]=s,t[2]=n,t[3]=a,t[4]=e[1],t[5]=e[5],t[6]=o,t[7]=r,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],n=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,t[7]=n}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],a=e[5],o=e[6],l=e[7],c=e[8],u=e[9],h=e[10],p=e[11],d=e[12],A=e[13],f=e[14],I=e[15];return d*u*o*n-c*A*o*n-d*a*h*n+r*A*h*n+c*a*f*n-r*u*f*n-d*u*i*l+c*A*i*l+d*s*h*l-t*A*h*l-c*s*f*l+t*u*f*l+d*a*i*p-r*A*i*p-d*s*o*p+t*A*o*p+r*s*f*p-t*a*f*p-c*a*i*I+r*u*i*I+c*s*o*I-t*u*o*I-r*s*h*I+t*a*h*I},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8],h=e[9],p=e[10],d=e[11],A=e[12],f=e[13],I=e[14],m=e[15],y=s*o-i*a,v=s*l-n*a,w=s*c-r*a,g=i*l-n*o,T=i*c-r*o,E=n*c-r*l,b=u*f-h*A,_=u*I-p*A,D=u*m-d*A,P=h*I-p*f,C=h*m-d*f,R=p*m-d*I,B=1/(y*R-v*C+w*P+g*D-T*_+E*b);return t[0]=(o*R-l*C+c*P)*B,t[1]=(-i*R+n*C-r*P)*B,t[2]=(f*E-I*T+m*g)*B,t[3]=(-h*E+p*T-d*g)*B,t[4]=(-a*R+l*D-c*_)*B,t[5]=(s*R-n*D+r*_)*B,t[6]=(-A*E+I*w-m*v)*B,t[7]=(u*E-p*w+d*v)*B,t[8]=(a*C-o*D+c*b)*B,t[9]=(-s*C+i*D-r*b)*B,t[10]=(A*T-f*w+m*y)*B,t[11]=(-u*T+h*w-d*y)*B,t[12]=(-a*P+o*_-l*b)*B,t[13]=(s*P-i*_+n*b)*B,t[14]=(-A*g+f*v-I*y)*B,t[15]=(u*g-h*v+p*y)*B,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||h.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||h.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new o(3);return(t,s,i,n)=>(e[0]=t,e[1]=s,e[2]=i,h.translationMat4v(e,n))})(),translationMat4s:(e,t)=>h.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>h.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const n=i[3];i[0]+=n*e,i[1]+=n*t,i[2]+=n*s;const r=i[7];i[4]+=r*e,i[5]+=r*t,i[6]+=r*s;const a=i[11];i[8]+=a*e,i[9]+=a*t,i[10]+=a*s;const o=i[15];return i[12]+=o*e,i[13]+=o*t,i[14]+=o*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=h.normalizeVec4([t[0],t[1],t[2],0],[]),n=Math.sin(e),r=Math.cos(e),a=1-r,o=i[0],l=i[1],c=i[2];let u,p,d,A,f,I;return u=o*l,p=l*c,d=c*o,A=o*n,f=l*n,I=c*n,(s=s||h.mat4())[0]=a*o*o+r,s[1]=a*u+I,s[2]=a*d-f,s[3]=0,s[4]=a*u-I,s[5]=a*l*l+r,s[6]=a*p+A,s[7]=0,s[8]=a*d+f,s[9]=a*p-A,s[10]=a*c*c+r,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,n)=>h.rotationMat4v(e,[t,s,i],n),scalingMat4v:(e,t=h.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=h.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new o(3);return(t,s,i,n)=>(e[0]=t,e[1]=s,e[2]=i,h.scalingMat4v(e,n))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],n=e[2];return t[0]*=s,t[4]*=i,t[8]*=n,t[1]*=s,t[5]*=i,t[9]*=n,t[2]*=s,t[6]*=i,t[10]*=n,t[3]*=s,t[7]*=i,t[11]*=n,t},scalingMat4s:e=>h.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=h.mat4()){const i=e[0],n=e[1],r=e[2],a=e[3],o=i+i,l=n+n,c=r+r,u=i*o,p=i*l,d=i*c,A=n*l,f=n*c,I=r*c,m=a*o,y=a*l,v=a*c;return s[0]=1-(A+I),s[1]=p+v,s[2]=d-y,s[3]=0,s[4]=p-v,s[5]=1-(u+I),s[6]=f+m,s[7]=0,s[8]=d+y,s[9]=f-m,s[10]=1-(u+A),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=h.vec4()){const i=h.clamp,n=e[0],r=e[4],a=e[8],o=e[1],l=e[5],c=e[9],u=e[2],p=e[6],d=e[10];return"XYZ"===t?(s[1]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-c,d),s[2]=Math.atan2(-r,n)):(s[0]=Math.atan2(p,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[1]=Math.atan2(a,d),s[2]=Math.atan2(o,l)):(s[1]=Math.atan2(-u,n),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(p,-1,1)),Math.abs(p)<.99999?(s[1]=Math.atan2(-u,d),s[2]=Math.atan2(-r,l)):(s[1]=0,s[2]=Math.atan2(o,n))):"ZYX"===t?(s[1]=Math.asin(-i(u,-1,1)),Math.abs(u)<.99999?(s[0]=Math.atan2(p,d),s[2]=Math.atan2(o,n)):(s[0]=0,s[2]=Math.atan2(-r,l))):"YZX"===t?(s[2]=Math.asin(i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(-c,l),s[1]=Math.atan2(-u,n)):(s[0]=0,s[1]=Math.atan2(a,d))):"XZY"===t&&(s[2]=Math.asin(-i(r,-1,1)),Math.abs(r)<.99999?(s[0]=Math.atan2(p,l),s[1]=Math.atan2(a,n)):(s[0]=Math.atan2(-c,d),s[1]=0)),s},composeMat4:(e,t,s,i=h.mat4())=>(h.quaternionToRotationMat4(t,i),h.scaleMat4v(s,i),h.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new o(3),t=new o(16);return function(s,i,n,r){e[0]=s[0],e[1]=s[1],e[2]=s[2];let a=h.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const o=h.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=h.lenVec3(e);h.determinantMat4(s)<0&&(a=-a),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const c=1/a,u=1/o,p=1/l;return t[0]*=c,t[1]*=c,t[2]*=c,t[4]*=u,t[5]*=u,t[6]*=u,t[8]*=p,t[9]*=p,t[10]*=p,h.mat4ToQuaternion(t,n),r[0]=a,r[1]=o,r[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=h.mat4());const n=e[0],r=e[1],a=e[2],o=s[0],l=s[1],c=s[2],u=t[0],p=t[1],d=t[2];if(n===u&&r===p&&a===d)return h.identityMat4();let A,f,I,m,y,v,w,g,T,E;return A=n-u,f=r-p,I=a-d,E=1/Math.sqrt(A*A+f*f+I*I),A*=E,f*=E,I*=E,m=l*I-c*f,y=c*A-o*I,v=o*f-l*A,E=Math.sqrt(m*m+y*y+v*v),E?(E=1/E,m*=E,y*=E,v*=E):(m=0,y=0,v=0),w=f*v-I*y,g=I*m-A*v,T=A*y-f*m,E=Math.sqrt(w*w+g*g+T*T),E?(E=1/E,w*=E,g*=E,T*=E):(w=0,g=0,T=0),i[0]=m,i[1]=w,i[2]=A,i[3]=0,i[4]=y,i[5]=g,i[6]=f,i[7]=0,i[8]=v,i[9]=T,i[10]=I,i[11]=0,i[12]=-(m*n+y*r+v*a),i[13]=-(w*n+g*r+T*a),i[14]=-(A*n+f*r+I*a),i[15]=1,i},lookAtMat4c:(e,t,s,i,n,r,a,o,l)=>h.lookAtMat4v([e,t,s],[i,n,r],[a,o,l],[]),orthoMat4c(e,t,s,i,n,r,a){a||(a=h.mat4());const o=t-e,l=i-s,c=r-n;return a[0]=2/o,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/c,a[11]=0,a[12]=-(e+t)/o,a[13]=-(i+s)/l,a[14]=-(r+n)/c,a[15]=1,a},frustumMat4v(e,t,s){s||(s=h.mat4());const i=[e[0],e[1],e[2],0],n=[t[0],t[1],t[2],0];h.addVec4(n,i,l),h.subVec4(n,i,c);const r=2*i[2],a=c[0],o=c[1],u=c[2];return s[0]=r/a,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r/o,s[6]=0,s[7]=0,s[8]=l[0]/a,s[9]=l[1]/o,s[10]=-l[2]/u,s[11]=-1,s[12]=0,s[13]=0,s[14]=-r*n[2]/u,s[15]=0,s},frustumMat4(e,t,s,i,n,r,a){a||(a=h.mat4());const o=t-e,l=i-s,c=r-n;return a[0]=2*n/o,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2*n/l,a[6]=0,a[7]=0,a[8]=(t+e)/o,a[9]=(i+s)/l,a[10]=-(r+n)/c,a[11]=-1,a[12]=0,a[13]=0,a[14]=-r*n*2/c,a[15]=0,a},perspectiveMat4(e,t,s,i,n){const r=[],a=[];return r[2]=s,a[2]=i,a[1]=r[2]*Math.tan(e/2),r[1]=-a[1],a[0]=a[1]*t,r[0]=-a[0],h.frustumMat4v(r,a,n)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,s=h.vec3()){const i=t[0],n=t[1],r=t[2];return s[0]=e[0]*i+e[4]*n+e[8]*r+e[12],s[1]=e[1]*i+e[5]*n+e[9]*r+e[13],s[2]=e[2]*i+e[6]*n+e[10]*r+e[14],s},transformPoint4:(e,t,s=h.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],n=t.length;let r,a,o,l;const c=e[0],u=e[1],h=e[2],p=e[3],d=e[4],A=e[5],f=e[6],I=e[7],m=e[8],y=e[9],v=e[10],w=e[11],g=e[12],T=e[13],E=e[14],b=e[15];let _;for(let e=0;e<n;++e)l=t[e],r=l[0],a=l[1],o=l[2],_=i[e]||(i[e]=[0,0,0]),_[0]=c*r+d*a+m*o+g,_[1]=u*r+A*a+y*o+T,_[2]=h*r+f*a+v*o+E,_[3]=p*r+I*a+w*o+b;return i.length=n,i},transformPositions3(e,t,s=t){let i;const n=t.length;let r,a,o;const l=e[0],c=e[1],u=e[2];e[3];const h=e[4],p=e[5],d=e[6];e[7];const A=e[8],f=e[9],I=e[10];e[11];const m=e[12],y=e[13],v=e[14];for(e[15],i=0;i<n;i+=3)r=t[i+0],a=t[i+1],o=t[i+2],s[i+0]=l*r+h*a+A*o+m,s[i+1]=c*r+p*a+f*o+y,s[i+2]=u*r+d*a+I*o+v;return s},transformPositions4(e,t,s=t){let i;const n=t.length;let r,a,o;const l=e[0],c=e[1],u=e[2],h=e[3],p=e[4],d=e[5],A=e[6],f=e[7],I=e[8],m=e[9],y=e[10],v=e[11],w=e[12],g=e[13],T=e[14],E=e[15];for(i=0;i<n;i+=4)r=t[i+0],a=t[i+1],o=t[i+2],s[i+0]=l*r+p*a+I*o+w,s[i+1]=c*r+d*a+m*o+g,s[i+2]=u*r+A*a+y*o+T,s[i+3]=h*r+f*a+v*o+E;return s},transformVec3(e,t,s){const i=t[0],n=t[1],r=t[2];return(s=s||this.vec3())[0]=e[0]*i+e[4]*n+e[8]*r,s[1]=e[1]*i+e[5]*n+e[9]*r,s[2]=e[2]*i+e[6]*n+e[10]*r,s},transformVec4(e,t,s){const i=t[0],n=t[1],r=t[2],a=t[3];return(s=s||h.vec4())[0]=e[0]*i+e[4]*n+e[8]*r+e[12]*a,s[1]=e[1]*i+e[5]*n+e[9]*r+e[13]*a,s[2]=e[2]*i+e[6]*n+e[10]*r+e[14]*a,s[3]=e[3]*i+e[7]*n+e[11]*r+e[15]*a,s},rotateVec2(e,t,s,i=e){const n=Math.cos(s),r=Math.sin(s),a=e[0]-t[0],o=e[1]-t[1];return i[0]=a*n-o*r+t[0],i[1]=a*r+o*n+t[1],e},rotateVec3X(e,t,s,i){const n=[],r=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],r[0]=n[0],r[1]=n[1]*Math.cos(s)-n[2]*Math.sin(s),r[2]=n[1]*Math.sin(s)+n[2]*Math.cos(s),i[0]=r[0]+t[0],i[1]=r[1]+t[1],i[2]=r[2]+t[2],i},rotateVec3Y(e,t,s,i){const n=[],r=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],r[0]=n[2]*Math.sin(s)+n[0]*Math.cos(s),r[1]=n[1],r[2]=n[2]*Math.cos(s)-n[0]*Math.sin(s),i[0]=r[0]+t[0],i[1]=r[1]+t[1],i[2]=r[2]+t[2],i},rotateVec3Z(e,t,s,i){const n=[],r=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],r[0]=n[0]*Math.cos(s)-n[1]*Math.sin(s),r[1]=n[0]*Math.sin(s)+n[1]*Math.cos(s),r[2]=n[2],i[0]=r[0]+t[0],i[1]=r[1]+t[1],i[2]=r[2]+t[2],i},projectVec4(e,t){const s=1/e[3];return(t=t||h.vec2())[0]=e[0]*s,t[1]=e[1]*s,t},unprojectVec3:(()=>{const e=new o(16),t=new o(16),s=new o(16);return function(i,n,r,a){return this.transformVec3(this.mulMat4(this.inverseMat4(n,e),this.inverseMat4(r,t),s),i,a)}})(),lerpVec3(e,t,s,i,n,r){const a=r||h.vec3(),o=(e-t)/(s-t);return a[0]=i[0]+o*(n[0]-i[0]),a[1]=i[1]+o*(n[1]-i[1]),a[2]=i[2]+o*(n[2]-i[2]),a},lerpMat4(e,t,s,i,n,r){const a=r||h.mat4(),o=(e-t)/(s-t);return a[0]=i[0]+o*(n[0]-i[0]),a[1]=i[1]+o*(n[1]-i[1]),a[2]=i[2]+o*(n[2]-i[2]),a[3]=i[3]+o*(n[3]-i[3]),a[4]=i[4]+o*(n[4]-i[4]),a[5]=i[5]+o*(n[5]-i[5]),a[6]=i[6]+o*(n[6]-i[6]),a[7]=i[7]+o*(n[7]-i[7]),a[8]=i[8]+o*(n[8]-i[8]),a[9]=i[9]+o*(n[9]-i[9]),a[10]=i[10]+o*(n[10]-i[10]),a[11]=i[11]+o*(n[11]-i[11]),a[12]=i[12]+o*(n[12]-i[12]),a[13]=i[13]+o*(n[13]-i[13]),a[14]=i[14]+o*(n[14]-i[14]),a[15]=i[15]+o*(n[15]-i[15]),a},flatten(e){const t=[];let s,i,n,r,a;for(s=0,i=e.length;s<i;s++)for(a=e[s],n=0,r=a.length;n<r;n++)t.push(a[n]);return t},identityQuaternion:(e=h.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=h.vec4()){const i=e[0]*h.DEGTORAD/2,n=e[1]*h.DEGTORAD/2,r=e[2]*h.DEGTORAD/2,a=Math.cos(i),o=Math.cos(n),l=Math.cos(r),c=Math.sin(i),u=Math.sin(n),p=Math.sin(r);return"XYZ"===t?(s[0]=c*o*l+a*u*p,s[1]=a*u*l-c*o*p,s[2]=a*o*p+c*u*l,s[3]=a*o*l-c*u*p):"YXZ"===t?(s[0]=c*o*l+a*u*p,s[1]=a*u*l-c*o*p,s[2]=a*o*p-c*u*l,s[3]=a*o*l+c*u*p):"ZXY"===t?(s[0]=c*o*l-a*u*p,s[1]=a*u*l+c*o*p,s[2]=a*o*p+c*u*l,s[3]=a*o*l-c*u*p):"ZYX"===t?(s[0]=c*o*l-a*u*p,s[1]=a*u*l+c*o*p,s[2]=a*o*p-c*u*l,s[3]=a*o*l+c*u*p):"YZX"===t?(s[0]=c*o*l+a*u*p,s[1]=a*u*l+c*o*p,s[2]=a*o*p-c*u*l,s[3]=a*o*l-c*u*p):"XZY"===t&&(s[0]=c*o*l-a*u*p,s[1]=a*u*l-c*o*p,s[2]=a*o*p+c*u*l,s[3]=a*o*l+c*u*p),s},mat4ToQuaternion(e,t=h.vec4()){const s=e[0],i=e[4],n=e[8],r=e[1],a=e[5],o=e[9],l=e[2],c=e[6],u=e[10];let p;const d=s+a+u;return d>0?(p=.5/Math.sqrt(d+1),t[3]=.25/p,t[0]=(c-o)*p,t[1]=(n-l)*p,t[2]=(r-i)*p):s>a&&s>u?(p=2*Math.sqrt(1+s-a-u),t[3]=(c-o)/p,t[0]=.25*p,t[1]=(i+r)/p,t[2]=(n+l)/p):a>u?(p=2*Math.sqrt(1+a-s-u),t[3]=(n-l)/p,t[0]=(i+r)/p,t[1]=.25*p,t[2]=(o+c)/p):(p=2*Math.sqrt(1+u-s-a),t[3]=(r-i)/p,t[0]=(n+l)/p,t[1]=(o+c)/p,t[2]=.25*p),t},vec3PairToQuaternion(e,t,s=h.vec4()){const i=Math.sqrt(h.dotVec3(e,e)*h.dotVec3(t,t));let n=i+h.dotVec3(e,t);return n<1e-8*i?(n=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):h.cross3Vec3(e,t,s),s[3]=n,h.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=h.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new o(16);return(t,s,i)=>(i=i||h.vec3(),h.quaternionToRotationMat4(t,e),h.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=h.vec4()){const i=e[0],n=e[1],r=e[2],a=e[3],o=t[0],l=t[1],c=t[2],u=t[3];return s[0]=a*o+i*u+n*c-r*l,s[1]=a*l+n*u+r*o-i*c,s[2]=a*c+r*u+i*l-n*o,s[3]=a*u-i*o-n*l-r*c,s},vec3ApplyQuaternion(e,t,s=h.vec3()){const i=t[0],n=t[1],r=t[2],a=e[0],o=e[1],l=e[2],c=e[3],u=c*i+o*r-l*n,p=c*n+l*i-a*r,d=c*r+a*n-o*i,A=-a*i-o*n-l*r;return s[0]=u*c+A*-a+p*-l-d*-o,s[1]=p*c+A*-o+d*-a-u*-l,s[2]=d*c+A*-l+u*-o-p*-a,s},quaternionToMat4(e,t){t=h.identityMat4(t);const s=e[0],i=e[1],n=e[2],r=e[3],a=2*s,o=2*i,l=2*n,c=a*r,u=o*r,p=l*r,d=a*s,A=o*s,f=l*s,I=o*i,m=l*i,y=l*n;return t[0]=1-(I+y),t[1]=A+p,t[2]=f-u,t[4]=A-p,t[5]=1-(d+y),t[6]=m+c,t[8]=f+u,t[9]=m-c,t[10]=1-(d+I),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],n=e[2],r=e[3],a=s+s,o=i+i,l=n+n,c=s*a,u=s*o,h=s*l,p=i*o,d=i*l,A=n*l,f=r*a,I=r*o,m=r*l;return t[0]=1-(p+A),t[4]=u-m,t[8]=h+I,t[1]=u+m,t[5]=1-(c+A),t[9]=d-f,t[2]=h-I,t[6]=d+f,t[10]=1-(c+p),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const s=h.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>h.normalizeQuaternion(h.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=h.vec4()){const s=(e=h.normalizeQuaternion(e,u))[3],i=2*Math.acos(s),n=Math.sqrt(1-s*s);return n<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n),t[3]=i,t},AABB3:e=>new o(e||6),AABB2:e=>new o(e||4),OBB3:e=>new o(e||32),OBB2:e=>new o(e||16),Sphere3:(e,t,s,i)=>new o([e,t,s,i]),transformOBB3(e,t,s=t){let i;const n=t.length;let r,a,o;const l=e[0],c=e[1],u=e[2],h=e[3],p=e[4],d=e[5],A=e[6],f=e[7],I=e[8],m=e[9],y=e[10],v=e[11],w=e[12],g=e[13],T=e[14],E=e[15];for(i=0;i<n;i+=4)r=t[i+0],a=t[i+1],o=t[i+2],s[i+0]=l*r+p*a+I*o+w,s[i+1]=c*r+d*a+m*o+g,s[i+2]=u*r+A*a+y*o+T,s[i+3]=h*r+f*a+v*o+E;return s},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:(()=>{const e=new o(3),t=new o(3),s=new o(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],h.subVec3(t,e,s),Math.abs(h.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new o(3),t=new o(3),s=new o(3);return(i,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const r=h.subVec3(t,e,s),a=n[0]-i[0],o=i[3]-n[0],l=n[1]-i[1],c=i[4]-n[1],u=n[2]-i[2],p=i[5]-n[2];return r[0]+=a>o?a:o,r[1]+=l>c?l:c,r[2]+=u>p?u:p,Math.abs(h.lenVec3(r))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||h.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||h.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=h.AABB3())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MAX_DOUBLE,e[3]=h.MIN_DOUBLE,e[4]=h.MIN_DOUBLE,e[5]=h.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=h.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new o(3);return(t,s,i)=>{s=s||h.AABB3();let n,r,a,o=h.MAX_DOUBLE,l=h.MAX_DOUBLE,c=h.MAX_DOUBLE,u=h.MIN_DOUBLE,p=h.MIN_DOUBLE,d=h.MIN_DOUBLE;for(let s=0,A=t.length;s<A;s+=3)i?(e[0]=t[s+0],e[1]=t[s+1],e[2]=t[s+2],h.decompressPosition(e,i,e),n=e[0],r=e[1],a=e[2]):(n=t[s+0],r=t[s+1],a=t[s+2]),n<o&&(o=n),r<l&&(l=r),a<c&&(c=a),n>u&&(u=n),r>p&&(p=r),a>d&&(d=a);return s[0]=o,s[1]=l,s[2]=c,s[3]=u,s[4]=p,s[5]=d,s}})(),OBB3ToAABB3(e,t=h.AABB3()){let s,i,n,r=h.MAX_DOUBLE,a=h.MAX_DOUBLE,o=h.MAX_DOUBLE,l=h.MIN_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t+=4)s=e[t+0],i=e[t+1],n=e[t+2],s<r&&(r=s),i<a&&(a=i),n<o&&(o=n),s>l&&(l=s),i>c&&(c=i),n>u&&(u=n);return t[0]=r,t[1]=a,t[2]=o,t[3]=l,t[4]=c,t[5]=u,t},points3ToAABB3(e,t=h.AABB3()){let s,i,n,r=h.MAX_DOUBLE,a=h.MAX_DOUBLE,o=h.MAX_DOUBLE,l=h.MIN_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t++)s=e[t][0],i=e[t][1],n=e[t][2],s<r&&(r=s),i<a&&(a=i),n<o&&(o=n),s>l&&(l=s),i>c&&(c=i),n>u&&(u=n);return t[0]=r,t[1]=a,t[2]=o,t[3]=l,t[4]=c,t[5]=u,t},points3ToSphere3:(()=>{const e=new o(3);return(t,s)=>{s=s||h.vec4();let i,n=0,r=0,a=0;const o=t.length;for(i=0;i<o;i++)n+=t[i][0],r+=t[i][1],a+=t[i][2];s[0]=n/o,s[1]=r/o,s[2]=a/o;let l,c=0;for(i=0;i<o;i++)l=Math.abs(h.lenVec3(h.subVec3(t[i],s,e))),l>c&&(c=l);return s[3]=c,s}})(),positions3ToSphere3:(()=>{const e=new o(3),t=new o(3);return(s,i)=>{i=i||h.vec4();let n,r=0,a=0,o=0;const l=s.length;let c=0;for(n=0;n<l;n+=3)r+=s[n],a+=s[n+1],o+=s[n+2];const u=l/3;let p;for(i[0]=r/u,i[1]=a/u,i[2]=o/u,n=0;n<l;n+=3)e[0]=s[n],e[1]=s[n+1],e[2]=s[n+2],p=Math.abs(h.lenVec3(h.subVec3(e,i,t))),p>c&&(c=p);return i[3]=c,i}})(),OBB3ToSphere3:(()=>{const e=new o(3),t=new o(3);return(s,i)=>{i=i||h.vec4();let n,r=0,a=0,o=0;const l=s.length,c=l/4;for(n=0;n<l;n+=4)r+=s[n+0],a+=s[n+1],o+=s[n+2];i[0]=r/c,i[1]=a/c,i[2]=o/c;let u,p=0;for(n=0;n<l;n+=4)e[0]=s[n+0],e[1]=s[n+1],e[2]=s[n+2],u=Math.abs(h.lenVec3(h.subVec3(e,i,t))),u>p&&(p=u);return i[3]=p,i}})(),getSphere3Center:(e,t=h.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=h.vec3()){let s=0,i=0,n=0;for(var r=0,a=e.length;r<a;r+=3)s+=e[r+0],i+=e[r+1],n+=e[r+2];const o=e.length/3;return t[0]=s/o,t[1]=i/o,t[2]=n/o,t},expandAABB3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e),expandAABB3Point3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e),expandAABB3Points3(e,t){for(var s,i,n,r=0,a=t.length;r<a;r+=3)s=t[r],i=t[r+1],n=t[r+2],e[0]>s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>n&&(e[2]=n),e[3]<s&&(e[3]=s),e[4]<i&&(e[4]=i),e[5]<n&&(e[5]=n);return e},collapseAABB2:(e=h.AABB2())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MIN_DOUBLE,e[3]=h.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2],planeAABB3Intersect(e,t,s){let i,n;e[0]>0?(i=e[0]*s[0],n=e[0]*s[3]):(i=e[0]*s[3],n=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],n+=e[1]*s[4]):(i+=e[1]*s[4],n+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],n+=e[2]*s[5]):(i+=e[2]*s[5],n+=e[2]*s[2]);if(i<=-t&&n<=-t)return-1;return i>=-t&&n>=-t?1:0},OBB3ToAABB2(e,t=h.AABB2()){let s,i,n,r,a=h.MAX_DOUBLE,o=h.MAX_DOUBLE,l=h.MIN_DOUBLE,c=h.MIN_DOUBLE;for(let t=0,u=e.length;t<u;t+=4)s=e[t+0],i=e[t+1],n=e[t+3]||1,r=1/n,s*=r,i*=r,s<a&&(a=s),i<o&&(o=i),s>l&&(l=s),i>c&&(c=i);return t[0]=a,t[1]=o,t[2]=l,t[3]=c,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e),expandAABB2Point2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e),AABB2ToCanvas(e,t,s,i=e){const n=.5*(e[0]+1),r=.5*(e[1]+1),a=.5*(e[2]+1),o=.5*(e[3]+1);return i[0]=Math.floor(n*t),i[1]=s-Math.floor(o*s),i[2]=Math.floor(a*t),i[3]=s-Math.floor(r*s),i},tangentQuadraticBezier:(e,t,s,i)=>2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,n)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+3*e*e*n,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,s,i,n){const r=.5*(s-e),a=.5*(i-t),o=n*n;return(2*t-2*s+r+a)*(n*o)+(-3*t+3*s-2*r-a)*o+r*n+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,n){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,n)},triangleNormal(e,t,s,i=h.vec3()){const n=t[0]-e[0],r=t[1]-e[1],a=t[2]-e[2],o=s[0]-e[0],l=s[1]-e[1],c=s[2]-e[2],u=r*c-a*l,p=a*o-n*c,d=n*l-r*o,A=Math.sqrt(u*u+p*p+d*d);return 0===A?(i[0]=0,i[1]=0,i[2]=0):(i[0]=u/A,i[1]=p/A,i[2]=d/A),i},rayTriangleIntersect:(()=>{const e=new o(3),t=new o(3),s=new o(3),i=new o(3),n=new o(3);return(r,a,o,l,c,u)=>{u=u||h.vec3();const p=h.subVec3(l,o,e),d=h.subVec3(c,o,t),A=h.cross3Vec3(a,d,s),f=h.dotVec3(p,A);if(f<1e-6)return null;const I=h.subVec3(r,o,i),m=h.dotVec3(I,A);if(m<0||m>f)return null;const y=h.cross3Vec3(I,p,n),v=h.dotVec3(a,y);if(v<0||m+v>f)return null;const w=h.dotVec3(d,y)/f;return u[0]=r[0]+w*a[0],u[1]=r[1]+w*a[1],u[2]=r[2]+w*a[2],u}})(),rayPlaneIntersect:(()=>{const e=new o(3),t=new o(3),s=new o(3),i=new o(3);return(n,r,a,o,l,c)=>{c=c||h.vec3(),r=h.normalizeVec3(r,e);const u=h.subVec3(o,a,t),p=h.subVec3(l,a,s),d=h.cross3Vec3(u,p,i);h.normalizeVec3(d,d);const A=-h.dotVec3(a,d),f=-(h.dotVec3(n,d)+A)/h.dotVec3(r,d);return c[0]=n[0]+f*r[0],c[1]=n[1]+f*r[1],c[2]=n[2]+f*r[2],c}})(),cartesianToBarycentric:(()=>{const e=new o(3),t=new o(3),s=new o(3);return(i,n,r,a,o)=>{const l=h.subVec3(a,n,e),c=h.subVec3(r,n,t),u=h.subVec3(i,n,s),p=h.dotVec3(l,l),d=h.dotVec3(l,c),A=h.dotVec3(l,u),f=h.dotVec3(c,c),I=h.dotVec3(c,u),m=p*f-d*d;if(0===m)return null;const y=1/m,v=(f*A-d*I)*y,w=(p*I-d*A)*y;return o[0]=1-v-w,o[1]=w,o[2]=v,o}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,n=h.vec3()){const r=e[0],a=e[1],o=e[2];return n[0]=t[0]*r+s[0]*a+i[0]*o,n[1]=t[1]*r+s[1]*a+i[1]*o,n[2]=t[2]*r+s[2]*a+i[2]*o,n},mergeVertices(e,t,s,i){const n={},r=[],a=[],o=t?[]:null,l=s?[]:null,c=[];let u,h,p,d;const A=1e4;let f,I,m=0;for(f=0,I=e.length;f<I;f+=3)u=e[f],h=e[f+1],p=e[f+2],d=`${Math.round(u*A)}_${Math.round(h*A)}_${Math.round(p*A)}`,void 0===n[d]&&(n[d]=a.length/3,a.push(u),a.push(h),a.push(p),t&&(o.push(t[f]),o.push(t[f+1]),o.push(t[f+2])),s&&(l.push(s[m]),l.push(s[m+1]))),r[f/3]=n[d],m+=2;for(f=0,I=i.length;f<I;f++)c[f]=r[i[f]];const y={positions:a,indices:c};return o&&(y.normals=o),l&&(y.uv=l),y},buildNormals:(()=>{const e=new o(3),t=new o(3),s=new o(3),i=new o(3),n=new o(3),r=new o(3);return(a,o,l)=>{let c,u;const p=new Array(a.length/3);let d,A,f,I,m,y,v;for(c=0,u=o.length;c<u;c+=3){d=o[c],A=o[c+1],f=o[c+2],e[0]=a[3*d],e[1]=a[3*d+1],e[2]=a[3*d+2],t[0]=a[3*A],t[1]=a[3*A+1],t[2]=a[3*A+2],s[0]=a[3*f],s[1]=a[3*f+1],s[2]=a[3*f+2],h.subVec3(t,e,i),h.subVec3(s,e,n);const l=h.vec3();h.normalizeVec3(h.cross3Vec3(i,n,r),l),p[d]||(p[d]=[]),p[A]||(p[A]=[]),p[f]||(p[f]=[]),p[d].push(l),p[A].push(l),p[f].push(l)}for(l=l&&l.length===a.length?l:new Float32Array(a.length),c=0,u=p.length;c<u;c++){I=p[c].length,m=0,y=0,v=0;for(let e=0;e<I;e++)m+=p[c][e][0],y+=p[c][e][1],v+=p[c][e][2];l[3*c]=m/I,l[3*c+1]=y/I,l[3*c+2]=v/I}return l}})(),buildTangents:(()=>{const e=new o(3),t=new o(3),s=new o(3),i=new o(3),n=new o(3),r=new o(3),a=new o(3);return(o,l,c)=>{const u=new Float32Array(o.length);for(let p=0;p<l.length;p+=3){let d=l[p];const A=o.subarray(3*d,3*d+3),f=c.subarray(2*d,2*d+2);d=l[p+1];const I=o.subarray(3*d,3*d+3),m=c.subarray(2*d,2*d+2);d=l[p+2];const y=o.subarray(3*d,3*d+3),v=c.subarray(2*d,2*d+2),w=h.subVec3(I,A,e),g=h.subVec3(y,A,t),T=h.subVec2(m,f,s),E=h.subVec2(v,f,i),b=1/(T[0]*E[1]-T[1]*E[0]),_=h.mulVec3Scalar(h.subVec3(h.mulVec3Scalar(w,E[1],n),h.mulVec3Scalar(g,T[1],r),a),b,r);let D;for(let e=0;e<3;e++)D=3*l[p+e],u[D]+=_[0],u[D+1]+=_[1],u[D+2]+=_[2]}return u}})(),buildPickTriangles(e,t,s){const i=t.length,n=s?new Uint16Array(9*i):new Float32Array(9*i),r=new Uint8Array(12*i);let a,o,l,c,u,h,p=0,d=0,A=0;for(let s=0;s<i;s+=3)h=p>>24&255,u=p>>16&255,c=p>>8&255,l=255&p,o=t[s],a=3*o,n[d++]=e[a],n[d++]=e[a+1],n[d++]=e[a+2],r[A++]=l,r[A++]=c,r[A++]=u,r[A++]=h,o=t[s+1],a=3*o,n[d++]=e[a],n[d++]=e[a+1],n[d++]=e[a+2],r[A++]=l,r[A++]=c,r[A++]=u,r[A++]=h,o=t[s+2],a=3*o,n[d++]=e[a],n[d++]=e[a+1],n[d++]=e[a+2],r[A++]=l,r[A++]=c,r[A++]=u,r[A++]=h,p++;return{positions:n,colors:r}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,n={},r=[],a={};let o,l,c,u,p;const d=1e4;let A,f,I,m,y,v;for(f=0,m=e.length;f<m;f+=3){A=f/3,l=e[f],c=e[f+1],u=e[f+2],p=`${Math.round(l*d)}_${Math.round(c*d)}_${Math.round(u*d)}`,void 0===n[p]?n[p]=[A]:n[p].push(A);const s=h.normalizeVec3([t[f],t[f+1],t[f+2]]);r[A]=s,o=h.vec4([s[0],s[1],s[2],1]),a[A]=o}for(p in n)if(n.hasOwnProperty(p)){const e=n[p],t=e.length;for(f=0;f<t;f++){const s=e[f];for(o=a[s],I=0;I<t;I++){if(f===I)continue;const t=e[I];y=r[s],v=r[t];Math.abs(h.angleVec3(y,v)/h.DEGTORAD)<i&&(o[0]+=v[0],o[1]+=v[1],o[2]+=v[2],o[3]+=1)}}}for(f=0,m=t.length;f<m;f+=3)o=a[f/3],t[f+0]=o[0]/o[3],t[f+1]=o[1]/o[3],t[f+2]=o[2]/o[3]},transformRay:(()=>{const e=new o(4),t=new o(4);return(s,i,n,r,a)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,h.transformVec4(s,e,t),r[0]=t[0],r[1]=t[1],r[2]=t[2],e[0]=n[0],e[1]=n[1],e[2]=n[2],h.transformVec3(s,e,t),h.normalizeVec3(t),a[0]=t[0],a[1]=t[1],a[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new o(16),t=new o(16),s=new o(4),i=new o(4),n=new o(4),r=new o(4);return(a,o,l,c,u,p)=>{const d=h.mulMat4(l,o,e),A=h.inverseMat4(d,t),f=a.width,I=a.height,m=(c[0]-f/2)/(f/2),y=-(c[1]-I/2)/(I/2);s[0]=m,s[1]=y,s[2]=-1,s[3]=1,h.transformVec4(A,s,i),h.mulVec4Scalar(i,1/i[3]),n[0]=m,n[1]=y,n[2]=1,n[3]=1,h.transformVec4(A,n,r),h.mulVec4Scalar(r,1/r[3]),u[0]=r[0],u[1]=r[1],u[2]=r[2],h.subVec3(r,i,p),h.normalizeVec3(p)}})(),canvasPosToLocalRay:(()=>{const e=new o(3),t=new o(3);return(s,i,n,r,a,o,l)=>{h.canvasPosToWorldRay(s,i,n,a,e,t),h.worldRayToLocalRay(r,e,t,o,l)}})(),worldRayToLocalRay:(()=>{const e=new o(16),t=new o(4),s=new o(4);return(i,n,r,a,o)=>{const l=h.inverseMat4(i,e);t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=1,h.transformVec4(l,t,s),a[0]=s[0],a[1]=s[1],a[2]=s[2],h.transformVec3(l,r,o)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,n,r){const a=new o(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let c,u;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,c=0,u=s.length;c<u;++c){var h=3*s[c];for(let e=0;e<3;++e){const t=3*i[h+e];n[t]<a[0]&&(a[0]=n[t]),n[t]>a[3]&&(a[3]=n[t]),n[t+1]<a[1]&&(a[1]=n[t+1]),n[t+1]>a[4]&&(a[4]=n[t+1]),n[t+2]<a[2]&&(a[2]=n[t+2]),n[t+2]>a[5]&&(a[5]=n[t+2])}}if(s.length<20||r>10)return l.triangles=s,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let p=0;e[1]>e[p]&&(p=1),e[2]>e[p]&&(p=2),l.splitDim=p;const d=(a[p]+a[p+3])/2,A=new Array(s.length);let f=0;const I=new Array(s.length);let m=0;for(c=0,u=s.length;c<u;++c){const e=i[h=3*s[c]],t=3*i[h+1],r=3*i[h+2];n[3*e+p]<=d||n[t+p]<=d||n[r+p]<=d?A[f++]=s[c]:I[m++]=s[c]}return A.length=f,I.length=m,l.left=t(A,i,n,r+1),l.right=t(I,i,n,r+1),l}return(e,s)=>{const i=e.length/3,n=new Array(i);for(let e=0;e<i;++e)n[e]=e;return t(n,e,s,0)}})(),decompressPosition(e,t,s){(s=s||e)[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,s=new Float32Array(e.length)){for(let i=0,n=e.length;i<n;i+=3)s[i+0]=e[i+0]*t[0]+t[12],s[i+1]=e[i+1]*t[5]+t[13],s[i+2]=e[i+2]*t[10]+t[14];return s},decompressUV(e,t,s){s[0]=e[0]*t[0]+t[6],s[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,s=new Float32Array(e.length)){for(let i=0,n=e.length;i<n;i+=3)s[i+0]=e[i+0]*t[0]+t[6],s[i+1]=e[i+1]*t[4]+t[7];return s},octDecodeVec2(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const n=1-Math.abs(s)-Math.abs(i);n<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const r=Math.sqrt(s*s+i*i+n*n);return t[0]=s/r,t[1]=i/r,t[2]=n/r,t},octDecodeVec2s(e,t){for(let s=0,i=0,n=e.length;s<n;s+=2){let n=e[s+0],r=e[s+1];n=(2*n+1)/255,r=(2*r+1)/255;const a=1-Math.abs(n)-Math.abs(r);a<0&&(n=(1-Math.abs(r))*(n>=0?1:-1),r=(1-Math.abs(n))*(r>=0?1:-1));const o=Math.sqrt(n*n+r*r+a*a);t[i+0]=n/o,t[i+1]=r/o,t[i+2]=a/o,i+=3}return t}};h.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],n=[];let r=0;const a=new Uint16Array(3),o=new Uint16Array(3),l=new Uint16Array(3),c=h.vec3(),u=h.vec3(),p=h.vec3(),d=h.vec3(),A=h.vec3(),f=h.vec3(),I=h.vec3();return function(m,y,v,w){!function(n,r){const a={};let o,l,c,u;const h=Math.pow(10,4);let p,d,A=0;for(p=0,d=n.length;p<d;p+=3)o=n[p],l=n[p+1],c=n[p+2],u=Math.round(o*h)+"_"+Math.round(l*h)+"_"+Math.round(c*h),void 0===a[u]&&(a[u]=A/3,e[A++]=o,e[A++]=l,e[A++]=c),t[p/3]=a[u];for(p=0,d=r.length;p<d;p++)i[p]=t[r[p]],s[i[p]]=r[p]}(m,y),function(t,s){r=0;for(let m=0,y=t;m<y;m+=3){const t=3*i[m],y=3*i[m+1],v=3*i[m+2];s?(a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],o[0]=e[y],o[1]=e[y+1],o[2]=e[y+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],h.decompressPosition(a,s,c),h.decompressPosition(o,s,u),h.decompressPosition(l,s,p)):(c[0]=e[t],c[1]=e[t+1],c[2]=e[t+2],u[0]=e[y],u[1]=e[y+1],u[2]=e[y+2],p[0]=e[v],p[1]=e[v+1],p[2]=e[v+2]),h.subVec3(p,u,d),h.subVec3(c,u,A),h.cross3Vec3(d,A,f),h.normalizeVec3(f,I);const w=n[r]||(n[r]={normal:h.vec3()});w.normal[0]=I[0],w.normal[1]=I[1],w.normal[2]=I[2],r++}}(y.length,v);const g=[],T=Math.cos(h.DEGTORAD*w),E={};let b,_,D,P,C,R,B,x,S,O,N,L=!1;for(let e=0,t=y.length;e<t;e+=3){const t=e/3;for(let s=0;s<3;s++)b=i[e+s],_=i[e+(s+1)%3],D=Math.min(b,_),P=Math.max(b,_),C=D+","+P,void 0===E[C]?E[C]={index1:D,index2:P,face1:t,face2:void 0}:E[C].face2=t}for(C in E)R=E[C],void 0!==R.face2&&(B=n[R.face1].normal,x=n[R.face2].normal,S=h.dotVec3(B,x),S>T)||(O=s[R.index1],N=s[R.index2],(!L&&O>65535||N>65535)&&(L=!0),g.push(O),g.push(N));return L?new Uint32Array(g):new Uint16Array(g)}}();class p{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const d={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var A=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],s=e[0].charCodeAt(0),i=s+e[1],n=s;n<i;++n)t.push(n);return String.fromCharCode.apply(null,t)})).join("");function f(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return A.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}const I=function(){for(var e={},t=window.location.search.substring(1).split("&"),s=0;s<t.length;s++){var i=t[s].split("=");if(void 0===e[i[0]])e[i[0]]=decodeURIComponent(i[1]);else if("string"==typeof e[i[0]]){var n=[e[i[0]],decodeURIComponent(i[1])];e[i[0]]=n}else e[i[0]].push(decodeURIComponent(i[1]))}return e}();const m={xmlToJson:function e(t,s){if(t.nodeType===t.TEXT_NODE){var i=t.nodeValue;if(null===i.match(/^\s+$/))return i}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var n={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var r=0;r<t.attributes.length;r++){var a=t.attributes[r];n[s[a.nodeName]||a.nodeName]=a.nodeValue}for(var o=0;o<t.childNodes.length;o++){(r=e(t.childNodes[o],s))&&n.children.push(r)}return n}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return f(t[0],2)+[1,4,7,10,13].map((function(e){return f((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var s=[],i=function(e){e.type===t&&s.push(e),(e.children||[]).forEach((function(e){i(e)}))};return i(e),s},timeout:function(e){return new Promise((function(t,s){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,s){var i=new XMLHttpRequest;i.open(e.method||"GET",e.url,!0),i.onload=function(n){console.log(e.url,i.readyState,i.status),4===i.readyState&&(200===i.status?t(i.responseXML):s(i.statusText))},i.send(null)}))},loadJSON:function(e,t,s){var i=e=>{};t=t||i,s=s||i;var n=new XMLHttpRequest;n.overrideMimeType("application/json"),n.open("GET",e,!0),n.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var n;try{n=JSON.parse(i)}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(n)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),n.addEventListener("error",(function(e){s(e)}),!1),n.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;const n=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(n){const e=!!n[2];var r=n[3];r=window.decodeURIComponent(r),e&&(r=window.atob(r));try{const e=new ArrayBuffer(r.length),s=new Uint8Array(e);for(var a=0;a<r.length;a++)s[a]=r.charCodeAt(a);window.setTimeout((function(){t(e)}),0)}catch(e){window.setTimeout((function(){s(e)}),0)}}else{const i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onreadystatechange=function(){4===i.readyState&&(200===i.status?t(i.response):s("loadArrayBuffer error : "+i.response))},i.send(null)}},queryString:I,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return m.isString(e)||m.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(m.isNumeric(e)||m.isString(e)?`${e}`:e.id)===(m.isNumeric(t)||m.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return m.apply(e,{})},apply:function(e,t){for(const s in e)e.hasOwnProperty(s)&&(t[s]=e[s]);return t},apply2:function(e,t){for(const s in e)e.hasOwnProperty(s)&&void 0!==e[s]&&null!==e[s]&&(t[s]=e[s]);return t},applyIf:function(e,t){for(const s in e)e.hasOwnProperty(s)&&(void 0!==t[s]&&null!==t[s]||(t[s]=e[s]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return m.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const s=new e.constructor(e.length+t.length);return s.set(e),s.set(t,e.length),s},flattenParentChildHierarchy:function(e){var t=[];return function e(s){s.id=s.uuid,delete s.oid,t.push(s);var i=s.children;if(i)for(var n=0,r=i.length;n<r;n++){i[n].parent=s.id,e(i[n])}s.children=[]}(e),t}},y={},v=new e,w=new p,g={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},T=[];let E,b=0,_=0;const D=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(D.scenes[e.id])return void console.error(`[ERROR] Scene ${m.inQuotes(e.id)} already exists`)}else e.id=v.addItem({});D.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;y[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},d.components.scenes++,e.once("destroyed",(()=>{v.removeItem(e.id),delete D.scenes[e.id],delete y[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in D.scenes)D.scenes.hasOwnProperty(t)&&(e=D.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete D.scenes[e.id]))},this.scheduleTask=function(e,t){w.push(e),w.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),n=0;for(;w.length>0&&(e<0||i<e);)t=w.shift(),s=w.shift(),s?t.call(s):t(),i=(new Date).getTime(),n++;return n},this.getNumTasks=function(){return w.length}},P=function(){let e=Date.now();if(E=e-b,b>0&&E>0){var t=1e3/E;_+=t,T.push(t),T.length>=30&&(_-=T.shift()),d.frame.fps=Math.round(_/T.length)}!function(e){const t=D.runTasks(e+10),s=D.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=s,d.frame.tasksBudget=10}(e),function(e){for(var t in g.time=e,D.scenes)if(D.scenes.hasOwnProperty(t)){var s=D.scenes[t];g.sceneId=t,g.startTime=s.startTime,g.deltaTime=null!=g.prevTime?g.time-g.prevTime:0,s.fire("tick",g,!0)}g.prevTime=e}(e),function(){const e=D.scenes,t=!1;let s,i,n,r,a;for(a in e)e.hasOwnProperty(a)&&(s=e[a],i=y[a],i||(i=y[a]={}),n=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==n&&(i.ticksPerOcclusionTest=n,i.renderCountdown=n),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=n),r=s.ticksPerRender,i.ticksPerRender!==r&&(i.ticksPerRender=r,i.renderCountdown=r),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=r))}(),b=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(P):requestAnimationFrame(P)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(P):requestAnimationFrame(P);class C{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 C))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let n;if(i)for(const s in i)i.hasOwnProperty(s)&&(n=i[s],this._eventCallDepth++,this._eventCallDepth<300?n.callback.call(n.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let n=this._eventSubs[t];n?this._eventSubsNum[t]++:(n={},this._eventSubs[t]=n,this._eventSubsNum[t]=1);const r=this._subIdMap.addItem();n[r]={callback:s,scope:i||this},this._subIdEvents[r]=t;const a=this._events[t];return void 0!==a&&s.call(i||this,a),r}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,n=this.on(e,(function(e){i.off(n),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+m.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let s=e.component;const i=e.sceneDefault,n=e.sceneSingleton,r=e.type,a=e.on,o=!1!==e.recompiles;if(s&&(m.isNumeric(s)||m.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+m.inQuotes(e))}if(!s)if(!0===n){const e=this.scene.types[r];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+m.inQuotes(s.id));if(r&&!s.isType(r))return void this.error("Expected a "+r+" type or subtype: "+s.type+" "+m.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let c,u,h;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(c=e.subs,u=0,h=c.length;u<h;u++)l.off(c[u]);delete this._attached[t],delete this._attachments[l.id];const i=e.params.onDetached;i&&(m.isFunction(i)?i(l):i.scope?i.callback.call(i.scope,l):i.callback(l)),e.managingLifecycle&&l.destroy()}if(s){const i={params:e,component:s,subs:[],managingLifecycle:false};i.subs.push(s.once("destroyed",(function(){i.params.component=null,this._attach(i.params)}),this)),o&&i.subs.push(s.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=s,this._attachments[s.id]=i;const n=e.onAttached;if(n&&(m.isFunction(n)?n(s):n.scope?n.callback.call(n.scope,s):n.callback(s)),a){let e,t,n,r;for(e in a)if(a.hasOwnProperty(e)){if(t=a[e],m.isFunction(t)?(n=t,r=null):(n=t.callback,r=t.scope),!n)continue;i.subs.push(s.on(e,n,r))}}}return o&&this.fire("dirty",this),this.fire(t,s),s}_checkComponent(e,t){if(!t.isComponent){if(!m.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}_checkComponent2(e,t){if(!t.isComponent){if(!m.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(t.scene.id===this.scene.id){for(var s=0,i=e.length;s<i;s++)if(e[s]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}_own(e){this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(()=>{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():D.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,s,i,n,r;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],s=t.component,i=t.subs,n=0,r=i.length;n<r;n++)s.off(i[n]);t.managingLifecycle&&s.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(s=this._ownedComponents[e],s.destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}const R=1,B=4,x=8,S=16,O=32,N=256,L=512,M=1024,F=2048,H=new Float32Array([0,0,0]),U=new Uint16Array([0,0,0]);class G{constructor(e,t,s,i,n,r){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=i,this._numTriangles=0;for(var a=0,o=this.meshes.length;a<o;a++){const e=this.meshes[a];e.parent=this,this._numTriangles+=e.numTriangles}this.id=s,this.originalSystemId=h.unglobalizeObjectId(e.id,s),this._flags=n,this._aabb=r,this._offsetAABB=h.AABB3(r),this._offset=h.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&e.scene._registerObject(this)}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get aabb(){return this._offsetAABB}get numTriangles(){return this._numTriangles}get visible(){return this._getFlag(R)}set visible(e){if(!!(this._flags&R)!==e){this._flags=e?this._flags|R:this._flags&~R;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this,e),this.model.glRedraw()}}get highlighted(){return this._getFlag(L)}set highlighted(e){if(!!(this._flags&L)!==e){this._flags=e?this._flags|L:this._flags&~L;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this,e),this.model.glRedraw()}}get xrayed(){return this._getFlag(N)}set xrayed(e){if(!!(this._flags&N)!==e){this._flags=e?this._flags|N:this._flags&~N;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this,e),this.model.glRedraw()}}get selected(){return this._getFlag(M)}set selected(e){if(!!(this._flags&M)!==e){this._flags=e?this._flags|M:this._flags&~M;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this,e),this.model.glRedraw()}}get edges(){return this._getFlag(F)}set edges(e){if(!!(this._flags&F)!==e){this._flags=e?this._flags|F:this._flags&~F;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get culledVFC(){return!!this._culledVFC}set culledVFC(e){this._culledVFC=e,this.internalSetCulled()}get culledLOD(){return!!this._culledLOD}set culledLOD(e){this._culledLOD=e,this.internalSetCulled()}get culled(){return!!this._culled}set culled(e){this._culled=e,this.internalSetCulled()}internalSetCulled(){let e=!!this._culled||!!this._culledLOD||!!this._culledVFC;if(!!(this._flags&B)!==e){this._flags=e?this._flags|B:this._flags&~B;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(S)}set clippable(e){if(!!(this._flags&S)!==e){this._flags=e?this._flags|S:this._flags&~S;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(O)}set collidable(e){if(!!(this._flags&O)!==e){this._flags=e?this._flags|O:this._flags&~O;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(x)}set pickable(e){if(!!(this._flags&x)!==e){this._flags=e?this._flags|x:this._flags&~x;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return H[0]=e[0]/255,H[1]=e[1]/255,H[2]=e[2]/255,H}set colorize(e){if(e){U[0]=Math.floor(255*e[0]),U[1]=Math.floor(255*e[1]),U[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(U)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t),this._colorizeUpdated=t}this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(i,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}get offset(){return this._offset}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._offsetAABB[0]=this._aabb[0]+this._offset[0],this._offsetAABB[1]=this._aabb[1]+this._offset[1],this._offsetAABB[2]=this._aabb[2]+this._offset[2],this._offsetAABB[3]=this._aabb[3]+this._offset[0],this._offsetAABB[4]=this._aabb[4]+this._offset[1],this._offsetAABB[5]=this._aabb[5]+this._offset[2],this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e.some((e=>0!==e))),this.model._aabbDirty=!0,this.model.glRedraw()}get castsShadow(){return!1}set castsShadow(e){}get receivesShadow(){return!1}set receivesShadow(e){}get saoEnabled(){return this.model.saoEnabled}getEachVertex(e){for(let t=0,s=this.meshes.length;t<s;t++)this.meshes[t].getEachVertex(e)}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this,!0),this.highlighted&&e._objectHighlightedUpdated(this,!0),this.xrayed&&e._objectXRayedUpdated(this,!0),this.selected&&e._objectSelectedUpdated(this,!0));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_finalize2(){for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1,!1),this.xrayed&&e._objectXRayedUpdated(this,!1),this.selected&&e._objectSelectedUpdated(this,!1),this.highlighted&&e._objectHighlightedUpdated(this,!1),this._opacityUpdated&&(this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1)),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const V=h.vec3(),j=function(){const e=new Float64Array(16),t=new Float64Array(4),s=new Float64Array(4);return function(i,n,r){return r=r||e,t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=1,h.transformVec4(i,t,s),h.setMat4Translation(i,s,r),r.slice()}}();function k(e,t,s){const i=Float32Array.from([e[0]])[0],n=e[0]-i,r=Float32Array.from([e[1]])[0],a=e[1]-r,o=Float32Array.from([e[2]])[0],l=e[2]-o;t[0]=i,t[1]=r,t[2]=o,s[0]=n,s[1]=a,s[2]=l}function Q(e,t,s,i=1e3){const n=h.getPositionsCenter(e,V),r=Math.round(n[0]/i)*i,a=Math.round(n[1]/i)*i,o=Math.round(n[2]/i)*i;s[0]=r,s[1]=a,s[2]=o;const l=0!==s[0]||0!==s[1]||0!==s[2];if(l)for(let s=0,i=e.length;s<i;s+=3)t[s+0]=e[s+0]-r,t[s+1]=e[s+1]-a,t[s+2]=e[s+2]-o;return l}function W(e,t,s,i){const n=h.dotVec3(t,s)+e,r=h.normalizeVec3(t,V);return h.mulVec3Scalar(r,-n,i),i}const z=1,K=4,Y=8,X=16,q=32,J=256,Z=512,$=1024,ee=2048,te=new Float32Array([0,0,0]),se=new Uint16Array([0,0,0]);class ie{constructor(e,t,s,i,n,r){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=i,this._numTriangles=0;for(var a=0,o=this.meshes.length;a<o;a++){const e=this.meshes[a];e.parent=this,this._numTriangles+=e.numTriangles}this.id=s,this.originalSystemId=h.unglobalizeObjectId(e.id,s),this._flags=n,this._aabb=r,this._offsetAABB=h.AABB3(r),this._offset=h.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&e.scene._registerObject(this)}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get aabb(){return this._offsetAABB}get numTriangles(){return this._numTriangles}get visible(){return this._getFlag(z)}set visible(e){if(!!(this._flags&z)!==e){this._flags=e?this._flags|z:this._flags&~z;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this,e),this.model.glRedraw()}}get highlighted(){return this._getFlag(Z)}set highlighted(e){if(!!(this._flags&Z)!==e){this._flags=e?this._flags|Z:this._flags&~Z;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this,e),this.model.glRedraw()}}get xrayed(){return this._getFlag(J)}set xrayed(e){if(!!(this._flags&J)!==e){this._flags=e?this._flags|J:this._flags&~J;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this,e),this.model.glRedraw()}}get selected(){return this._getFlag($)}set selected(e){if(!!(this._flags&$)!==e){this._flags=e?this._flags|$:this._flags&~$;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this,e),this.model.glRedraw()}}get edges(){return this._getFlag(ee)}set edges(e){if(!!(this._flags&ee)!==e){this._flags=e?this._flags|ee:this._flags&~ee;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get culledVFC(){return!!this._culledVFC}set culledVFC(e){this._culledVFC=e,this.internalSetCulled()}get culledLOD(){return!!this._culledLOD}set culledLOD(e){this._culledLOD=e,this.internalSetCulled()}get culled(){return!!this._culled}set culled(e){this._culled=e,this.internalSetCulled()}internalSetCulled(){let e=!!this._culled||!!this._culledLOD||!!this._culledVFC;if(!!(this._flags&K)!==e){this._flags=e?this._flags|K:this._flags&~K;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(X)}set clippable(e){if(!!(this._flags&X)!==e){this._flags=e?this._flags|X:this._flags&~X;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(q)}set collidable(e){if(!!(this._flags&q)!==e){this._flags=e?this._flags|q:this._flags&~q;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(Y)}set pickable(e){if(!!(this._flags&Y)!==e){this._flags=e?this._flags|Y:this._flags&~Y;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return te[0]=e[0]/255,te[1]=e[1]/255,te[2]=e[2]/255,te}set colorize(e){if(e){se[0]=Math.floor(255*e[0]),se[1]=Math.floor(255*e[1]),se[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(se)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t),this._colorizeUpdated=t}this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(i,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}get offset(){return this._offset}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._offsetAABB[0]=this._aabb[0]+this._offset[0],this._offsetAABB[1]=this._aabb[1]+this._offset[1],this._offsetAABB[2]=this._aabb[2]+this._offset[2],this._offsetAABB[3]=this._aabb[3]+this._offset[0],this._offsetAABB[4]=this._aabb[4]+this._offset[1],this._offsetAABB[5]=this._aabb[5]+this._offset[2],this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model._aabbDirty=!0,this.model.glRedraw()}get castsShadow(){return!1}set castsShadow(e){}get receivesShadow(){return!1}set receivesShadow(e){}get saoEnabled(){return this.model.saoEnabled}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this,!0),this.highlighted&&e._objectHighlightedUpdated(this,!0),this.xrayed&&e._objectXRayedUpdated(this,!0),this.selected&&e._objectSelectedUpdated(this,!0));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_finalize2(){for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1,!1),this.xrayed&&e._objectXRayedUpdated(this,!1),this.selected&&e._objectSelectedUpdated(this,!1),this.highlighted&&e._objectHighlightedUpdated(this,!1),this._opacityUpdated&&(this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1)),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const ne=h.vec4(),re=h.vec4();class ae extends C{constructor(e,t){super(e,t),this._entity=null,this._visible=null,this._worldPos=h.vec3(),this._origin=h.vec3(),this._rtcPos=h.vec3(),this._viewPos=h.vec3(),this._canvasPos=h.vec2(),this._occludable=!1,this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(h.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){ne.set(this._viewPos),ne[3]=1,h.transformPoint4(this.scene.camera.projMatrix,ne,re);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+re[0]/re[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-re[1]/re[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof G||this._entity instanceof ie?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),k(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class oe{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var n=this._wireClickable,r=n.style;r.border="solid "+this._thicknessClickable+"px "+this._color,r.position="absolute",r["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,r.width="0px",r.height="0px",r.visibility="visible",r.top="0px",r.left="0px",r["-webkit-transform-origin"]="0 0",r["-moz-transform-origin"]="0 0",r["-ms-transform-origin"]="0 0",r["-o-transform-origin"]="0 0",r["transform-origin"]="0 0",r["-webkit-transform"]="rotate(0deg)",r["-moz-transform"]="rotate(0deg)",r["-ms-transform"]="rotate(0deg)",r["-o-transform"]="rotate(0deg)",r.transform="rotate(0deg)",r.opacity=0,r["pointer-events"]="none",t.onContextMenu,e.appendChild(n),t.onMouseOver&&n.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&n.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&n.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&n.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get _visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){e=!!e,this._visible!==e&&(this._wire.style.visibility=e?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class le{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable";var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var n=this._dotClickable,r=n.style;r["border-radius"]="35px",r.border="solid 10px white",r.position="absolute",r["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,r.width="8px",r.height="8px",r.visibility="visible",r.top="0px",r.left="0px",r.opacity=0,r["pointer-events"]="none",t.onContextMenu,e.appendChild(n),t.onMouseOver&&n.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&n.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&n.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&n.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ce{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var n=e+.5*(s-e),r=t+.5*(i-t),a=this._label.style;a.left=Math.round(n)-20+"px",a.top=Math.round(r)-12+"px"}setPosBetweenWires(e,t,s,i,n,r){var a=(e+s+n)/3,o=(t+i+r)/3,l=this._label.style;l.left=Math.round(a)-20+"px",l.top=Math.round(o)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var ue=h.vec3(),he=h.vec3();class pe extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new ae(s,t.origin),this._cornerMarker=new ae(s,t.corner),this._targetMarker=new ae(s,t.target),this._originWorld=h.vec3(),this._cornerWorld=h.vec3(),this._targetWorld=h.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,n=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,r=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._cornerDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._targetDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._originWire=new oe(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._targetWire=new oe(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._angleLabel=new ce(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(h.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._cpDirty){const d=-.3,A=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],I=this._targetMarker.viewPos[2];if(A>d||f>d||I>d)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);h.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var n=i.top-m.top,r=i.left-m.left,a=e.canvas.boundary,o=a[2],l=a[3],c=0,u=0,p=t.length;u<p;u+=4)s[c]=r+Math.floor((1+t[u+0]/t[u+3])*o/2),s[c+1]=n+Math.floor((1-t[u+1]/t[u+3])*l/2),c+=2;if(this._originDot.setPos(s[0],s[1]),this._cornerDot.setPos(s[2],s[3]),this._targetDot.setPos(s[4],s[5]),this._originWire.setStartAndEnd(s[0],s[1],s[2],s[3]),this._targetWire.setStartAndEnd(s[2],s[3],s[4],s[5]),this._angleLabel.setPosBetweenWires(s[0],s[1],s[2],s[3],s[4],s[5]),h.subVec3(this._originWorld,this._cornerWorld,ue),h.subVec3(this._targetWorld,this._cornerWorld,he),!(0===ue[0]&&0===ue[1]&&0===ue[2]||0===he[0]&&0===he[1]&&0===he[2])){const e=this._approximate?" ~ ":" = ";h.normalizeVec3(ue),h.normalizeVec3(he);const t=Math.abs(h.angleVec3(ue,he));this._angle=t/h.DEGTORAD,this._angleLabel.setText(e+this._angle.toFixed(2)+"°")}else this._angleLabel.setText("");this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setCulled(!(this._visible&&this._angleVisible&&this.labelsVisible)),this._cpDirty=!1}}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get corner(){return this._cornerMarker}get target(){return this._targetMarker}get angle(){return this._update(),this._angle}get color(){return this._color}set color(e){this._originDot.setFillColor(e),this._cornerDot.setFillColor(e),this._targetDot.setFillColor(e),this._originWire.setColor(e||"blue"),this._targetWire.setColor(e||"red"),this._angleLabel.setFillColor(e||"#00BBFF"),this._color=e}set visible(e){e=!1!==e,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=!1!==e,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cpDirty=!0,this._needUpdate()}get originVisible(){return this._originVisible}set cornerVisible(e){e=!1!==e,this._cornerVisible=e,this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._cpDirty=!0,this._needUpdate()}get cornerVisible(){return this._cornerVisible}set targetVisible(e){e=!1!==e,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible),this._cpDirty=!0,this._needUpdate()}get targetVisible(){return this._targetVisible}set originWireVisible(e){e=!1!==e,this._originWireVisible=e,this._originWire.setVisible(this._visible&&this._originWireVisible),this._cpDirty=!0,this._needUpdate()}get originWireVisible(){return this._originWireVisible}set targetWireVisible(e){e=!1!==e,this._targetWireVisible=e,this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._cpDirty=!0,this._needUpdate()}get targetWireVisible(){return this._targetWireVisible}set angleVisible(e){e=!1!==e,this._angleVisible=e,this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}get angleVisible(){return this._angleVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._angleLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._cornerDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._originWire.setHighlighted(e),this._targetWire.setHighlighted(e),this._angleLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._cornerDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._originWire.setClickable(this._clickable),this._targetWire.setClickable(this._clickable),this._angleLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._originDot.destroy(),this._cornerDot.destroy(),this._targetDot.destroy(),this._originWire.destroy(),this._targetWire.destroy(),this._angleLabel.destroy(),super.destroy()}}class de extends C{constructor(e){super(e.viewer.scene),this.plugin=e,this._active=!1,this._state=0,this._currentAngleMeasurement=null,this._onMouseHoverSurface=null,this._onHoverNothing=null,this._onMouseHoverOff=null,this._onPickedNothing=null,this._onPickedSurface=null,this._onInputMouseDown=null,this._onInputMouseUp=null,this._onCanvasTouchStart=null,this._onCanvasTouchEnd=null}get active(){return this._active}activate(){if(this._active)return;const e=this.plugin,t=this.scene,s=e.viewer.cameraControl,i=t.canvas.canvas,n=t.input,r=t.pickSurfacePrecisionEnabled;let a=!1,o=null,l=h.vec3();const c=h.vec2();let u,p;const d=h.vec2(),A=h.vec2();h.vec3(),this._onMouseHoverSurface=s.on("hoverSurface",(e=>{if(a=!0,o=e.entity,l.set(e.worldPos),c.set(e.canvasPos),this._currentAngleMeasurement)switch(this._state){case 1:this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.entity=e.entity,this._currentAngleMeasurement.corner.worldPos=e.worldPos,i.style.cursor="pointer";break;case 2:this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.entity=e.entity,this._currentAngleMeasurement.target.worldPos=e.worldPos,i.style.cursor="pointer"}})),this._onInputMouseDown=n.on("mousedown",(e=>{u=e[0],p=e[1]})),this._onInputMouseUp=n.on("mouseup",(e=>{if(!(e[0]>u+5||e[0]<u-5||e[1]>p+5||e[1]<p-5))switch(this._state){case 0:if(a){if(r){const e=t.pick({canvasPos:c,pickSurface:!0,pickSurfacePrecision:r});e&&e.worldPos&&worldPos.set(e.worldPos)}this._currentAngleMeasurement=this.plugin.createMeasurement({id:h.createUUID(),origin:{entity:o,worldPos:l},corner:{entity:o,worldPos:l},target:{entity:o,worldPos:l},approximate:!0}),this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.angleVisible=!1,this._state=1,this.fire("measurementStart",this._currentAngleMeasurement)}break;case 1:if(a){if(r){const e=t.pick({canvasPos:c,pickSurface:!0,pickSurfacePrecision:!0});e&&e.worldPos&&(this._currentAngleMeasurement.corner.worldPos=e.worldPos)}this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._state=2}else this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._state=0,this.fire("measurementCancel",this._currentAngleMeasurement));break;case 2:if(a){if(r){const e=t.pick({canvasPos:c,pickSurface:!0,pickSurfacePrecision:!0});e&&e.worldPos&&(this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.approximate=!1)}this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this.fire("measurementEnd",this._currentAngleMeasurement),this._currentAngleMeasurement=null,this._state=0}else this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._state=0,this.fire("measurementCancel",this._currentAngleMeasurement))}})),this._onHoverNothing=s.on("hoverOff",(e=>{if(a=!1,this._currentAngleMeasurement){switch(this._state){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}i.style.cursor="default"}})),i.addEventListener("touchstart",this._onCanvasTouchStart=e=>{const t=e.touches,s=e.changedTouches;1===t.length&&1===s.length&&Ae(t[0],d)},{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=e=>{const s=e.touches,i=e.changedTouches;if(0===s.length&&1===i.length){if(Ae(i[0],A),A[0]>d[0]+5||A[0]<d[0]-5||A[1]>d[1]+5||A[1]<d[1]-5)return;const e=t.pick({canvasPos:A,pickSurface:!0,pickSurfacePrecision:!1});if(e&&e.worldPos)switch(this._state){case 0:this._currentAngleMeasurement=this.plugin.createMeasurement({id:h.createUUID(),origin:{entity:e.entity,worldPos:e.worldPos},corner:{entity:e.entity,worldPos:e.worldPos},target:{entity:e.entity,worldPos:e.worldPos},approximate:!0}),this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.clickable=!1,this._state=1,this.fire("measurementStart",this._currentAngleMeasurement);break;case 1:this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._state=2;break;case 2:this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.clickable=!0,this.fire("measurementEnd",this._currentAngleMeasurement),this._currentAngleMeasurement=null,this._state=0}else this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._state=0,this.fire("measurementCancel",this._currentAngleMeasurement))}},{passive:!0}),this._active=!0}deactivate(){if(!this._active)return;this.reset();const e=this.plugin.viewer.scene.input,t=this.plugin.viewer.cameraControl,s=this.plugin.viewer.scene.canvas.canvas;e.off(this._onInputMouseDown),e.off(this._onInputMouseUp),t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),s.removeEventListener("touchstart",this._onCanvasTouchStart),s.removeEventListener("touchend",this._onCanvasTouchEnd),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._state=0)}destroy(){this.deactivate(),super.destroy()}}const Ae=function(e,t){if(e){let s=e.target,i=0,n=0;for(;s.offsetParent;)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-i,t[1]=e.pageY-n}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class fe extends ae{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"<p></p>";m.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e);const t=document.createRange().createContextualFragment(e);this._marker=t.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(()=>{this.plugin.fire("markerClicked",this)})),this._marker.addEventListener("mouseenter",(()=>{this.plugin.fire("markerMouseEnter",this)})),this._marker.addEventListener("mouseleave",(()=>{this.plugin.fire("markerMouseLeave",this)})),this._marker.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);let e=this._labelHTML||"<p></p>";m.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e);const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=this.scene.canvas.boundary,t=e[0],s=e[1],i=this.canvasPos;this._marker.style.left=Math.floor(t+i[0])-12+"px",this._marker.style.top=Math.floor(s+i[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+i[0]+20)+"px",this._label.style.top=Math.floor(s+i[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const s=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),s)}return e}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const s=e[t];this.setField(t,s)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):this._marker.parentNode.removeChild(this._marker)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}const Ie=h.vec3(),me=h.vec3(),ye=h.vec3();class ve extends C{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const s=this._element;s&&(s.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const we={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},ge=document.createElement("canvas");if(ge){const e=ge.getContext("webgl",{antialias:!0})||ge.getContext("experimental-webgl",{antialias:!0});we.WEBGL=!!e,we.WEBGL&&(we.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?we.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?we.FS_MAX_FLOAT_PRECISION="mediump":we.FS_MAX_FLOAT_PRECISION="lowp":we.FS_MAX_FLOAT_PRECISION="mediump",we.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),we.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),we.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),we.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),we.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),we.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),we.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),we.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),we.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),we.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){we.SUPPORTED_EXTENSIONS[e]=!0})))}const Te=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Ee extends C{constructor(e,t={}){super(e,t),this._backgroundColor=h.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.optimizeResizeDetection=!0,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=null,n=null,r=null,a=null,o=null,l=null,c=null,u=null,p=0;this._tick=this.scene.on("tick",(()=>{if(p++,s._canvasSizeChanged=!1,s.optimizeResizeDetection&&p<10)return;p=0;const e=this.canvas,t=this._resolutionScale!==i,h=window.innerWidth!==n||window.innerHeight!==r,A=e.clientWidth!==a||e.clientHeight!==o,f=e.offsetLeft!==l||e.offsetTop!==c,I=e.parentElement;if(t||h||A||f||I!==u){if(s._canvasSizeChanged=!0,this._spinner._adjustPosition(),t||A||f){const s=e.clientWidth,i=e.clientHeight;if(t||A){let t,s=0;for(const e in D.scenes)D.scenes.hasOwnProperty(e)&&(t=D.scenes[e],s+=Math.round(t.canvas.canvas.clientWidth*this._resolutionScale*(t.canvas.canvas.clientHeight*this._resolutionScale)));d.memory.pixels=s,e.width=Math.round(e.clientWidth*this._resolutionScale),e.height=Math.round(e.clientHeight*this._resolutionScale)}const n=this.boundary;n[0]=e.offsetLeft,n[1]=e.offsetTop,n[2]=s,n[3]=i,t||this.fire("boundary",n),a=s,o=i}t&&(i=this._resolutionScale),h&&(n=window.innerWidth,r=window.innerHeight),f&&(l=e.offsetLeft,c=e.offsetTop),u=I}})),this._spinner=new ve(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+h.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<Te.length;e++)try{this.gl=this.canvas.getContext(Te[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));{const e=this.gl;let t="__",s=e.activeTexture;e.activeTexture=function(e){t!==e&&(t=e,s.call(this,e))};let i={},n=e.bindTexture;e.bindTexture=function(e,s){i[t]!==s&&(i[t]=s,n.call(this,e,s))}}this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}getSnapshot(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}readPixels(e,t,s,i){return this.scene._renderer.readPixels(e,t,s,i)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,super.destroy()}}class be{constructor(e){this._scene=e,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1}getRTCViewMatrix(e,t){let s=this._rtcViewMats[e];return s||(s=this._getNewMat(),j(this._scene.camera.viewMatrix,t,s),this._rtcViewMats[e]=s),s}getRTCPickViewMatrix(e,t){let s=this._rtcPickViewMats[e];if(!s){s=this._getNewMat();const i=this.pickViewMatrix||this._scene.camera.viewMatrix;j(i,t,s),this._rtcPickViewMats[e]=s}return s}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=h.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}class _e{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get worldPos(){return this.entity&&this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1}}class De{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e<t.length;e++)i.push(e+1+": "+t[e]+"\n");this.errors=[],this.errors.push(""),this.errors.push(e.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(i.join(""))}}else this.errors=["Failed to allocate"]}destroy(){}}class Pe{constructor(e,t){this.bindTexture=function(s,i){return!!s.bind(i)&&(e.uniform1i(t,i),!0)}}}class Ce{constructor(e,t){this._gl=e,this.location=t}bindArrayBuffer(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}const Re=new e({});function Be(e){const t=[];let s,i;for(let n=0,r=e.length;n<r;n++)s=e[n],i=s.indexOf("/"),i>0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function xe(e){console.error(e.join("\n"))}class Se{constructor(e,t){this.id=Re.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new De(e,e.VERTEX_SHADER,Be(this.source.vertex)),this._fragmentShader=new De(e,e.FRAGMENT_SHADER,Be(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void xe(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void xe(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void xe(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void xe(this.errors);let t,s,i,n,r;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 xe(this.errors);const a=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;s<a;++s)i=e.getActiveUniform(this.handle,s),i&&(n=i.name,"\0"===n[n.length-1]&&(n=n.substr(0,n.length-1)),r=e.getUniformLocation(this.handle,n),i.type===e.SAMPLER_2D||i.type===e.SAMPLER_CUBE||35682===i.type||e instanceof WebGL2RenderingContext&&(i.type===e.UNSIGNED_INT_SAMPLER_2D||i.type===e.INT_SAMPLER_2D)?this.samplers[n]=new Pe(e,r):this.uniforms[n]=r);const o=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(s=0;s<o;s++)t=e.getActiveAttrib(this.handle,s),t&&(r=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new Ce(e,r));this.allocated=!0}bind(){this.allocated&&this.gl.useProgram(this.handle)}getLocation(e){if(this.allocated)return this.uniforms[e]}getAttribute(e){if(this.allocated)return this.attributes[e]}bindTexture(e,t,s){if(!this.allocated)return!1;const i=this.samplers[e];return!!i&&i.bindTexture(t,s)}destroy(){this.allocated&&(Re.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}class Oe{constructor(e,t,s,i,n,r,a,o,l){switch(this._gl=e,this.type=t,this.allocated=!1,s.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=r,this.length=0,this.dataLength=i,this.numItems=0,this.itemSize=n,this.normalized=!!a,this.stride=o||0,this.offset=l||0,this._allocate(s)}_allocate(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ne{constructor(e,t){this.scene=e,this.aabb=h.AABB3(),this.origin=h.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t<this.numMarkers;t++)if(this.markerList[t]){const s=this.markerList[t].worldPos;this.positions[e++]=s[0],this.positions[e++]=s[1],this.positions[e++]=s[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}_buildAABB(){const e=this.aabb;h.collapseAABB3(e),h.expandAABB3Points3(e,this.positions);const t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}_buildVBOs(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(this.positions);this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,s=this.numMarkers;this.positionsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new Oe(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),s,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,s=e.boundary,i=s[2],n=s[3];let r=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const s=this.markerList[e];if(s.viewPos[2]>-t){s._setVisible(!1);continue}const a=s.canvasPos,o=a[0],l=a[1];o+10<0||l+10<0||o-10>i||l-10>n?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[r++]=o,this.pixels[r++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s];if(t.active){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const i=0===e;this.sectionPlanesActive[s]=i}else this.sectionPlanesActive[s]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const Le=h.vec3([1,0,0]),Me=h.vec3();class Fe{constructor(e,t){this._scene=e,this._renderBufferManager=t,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=e.camera.on("viewMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s||(s=new Ne(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new Ne(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}_buildOcclusionLayersList(){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}_buildShaderSource(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}_buildVertexShaderSource(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = 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,s=e._sectionPlanesState;if(this._program=new Se(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._aPosition=i.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,s=this._program,i=e._sectionPlanesState,n=e.camera,r=e.camera.project;if(s.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,n._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,s=this._occlusionLayersList.length;e<s;e++){const s=this._occlusionLayersList[e];if(s.update(),s.culledBySectionPlanes)continue;const r=s.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,j(n.viewMatrix,r));const a=i.sectionPlanes.length;if(a>0){const e=i.sectionPlanes;for(let i=0;i<a;i++){const n=this._uSectionPlanes[i];if(n){const a=s.sectionPlanesActive[i];if(t.uniform1i(n.active,a?1:0),a){const s=e[i];t.uniform3fv(n.pos,W(s.dist,s.dir,r,Me)),t.uniform3fv(n.dir,s.dir)}}}}this._aPosition.bindArrayBuffer(s.positionsBuf);const o=s.indicesBuf;o.bind(),t.drawElements(t.POINTS,o.numItems,o.itemType,0)}}doOcclusionTest(){{const e=this._scene.canvas.resolutionScale,t=255*Le[0],s=255*Le[1],i=255*Le[2];for(let n=0,r=this._occlusionLayersList.length;n<r;n++){const r=this._occlusionLayersList[n];for(let n=0;n<r.lenOcclusionTestList;n++){const a=r.occlusionTestList[n],o=2*n,l=this._readPixelBuf.read(Math.round(r.pixels[o]*e),Math.round(r.pixels[o+1]*e)),c=l[0]===t&&l[1]===s&&l[2]===i;a._setVisible(c)}}}}unbindRenderBuf(){this._readPixelBuf.unbind()}destroy(){if(!this.destroyed){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}const He=h.vec2();class Ue{constructor(e){this._scene=e,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null}render(e){if(this._build(),this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=h.mat4();return()=>(e&&h.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,n=i.sao,r=t.drawingBufferWidth,a=t.drawingBufferHeight,o=i.camera.project._state,l=o.near,c=o.far,u=o.matrix,p=this._getInverseProjectMat(),d=Math.random(),A="perspective"===i.camera.projection;He[0]=r,He[1]=a,t.viewport(0,0,r,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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,c),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,u),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,p),t.uniform1i(this._uPerspective,A),t.uniform1f(this._uScale,n.scale*(c/5)),t.uniform1f(this._uIntensity,n.intensity),t.uniform1f(this._uBias,n.bias),t.uniform1f(this._uKernelRadius,n.kernelRadius),t.uniform1f(this._uMinResolution,n.minResolution),t.uniform2fv(this._uViewport,He),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();s.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Se(s,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const i=new Float32Array([1,1,0,1,0,0,1,0]),n=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),r=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Oe(s,s.ARRAY_BUFFER,n,n.length,3,s.STATIC_DRAW),this._uvBuf=new Oe(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new Oe(s,s.ELEMENT_ARRAY_BUFFER,r,r.length,1,s.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const Ge=new Float32Array(ze(17,[0,1])),Ve=new Float32Array(ze(17,[1,0])),je=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(We(i,t));return s}(17,4)),ke=new Float32Array(2);class Qe{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Se(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Oe(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new Oe(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Oe(e,e.ELEMENT_ARRAY_BUFFER,i,i.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=h.mat4();return()=>(e&&h.inverseMat4(r.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,n=this._program,r=this._scene,a=i.drawingBufferWidth,o=i.drawingBufferHeight,l=r.camera.project._state,c=l.near,u=l.far;i.viewport(0,0,a,o),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),n.bind(),ke[0]=a,ke[1]=o,i.uniform2fv(this._uViewport,ke),i.uniform1f(this._uCameraNear,c),i.uniform1f(this._uCameraFar,u),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,Ve):i.uniform2fv(this._uSampleOffsets,Ge),i.uniform1fv(this._uSampleWeights,je);const p=e.getDepthTexture(),d=t.getTexture();n.bindTexture(this._uDepthTexture,p,0),n.bindTexture(this._uOcclusionTexture,d,1),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()}}function We(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function ze(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class Ke{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(e=null){if(this._touch(e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}_touch(e=null){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const n=i.createTexture();let r;i.bindTexture(i.TEXTURE_2D,n),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),e?i.texStorage2D(i.TEXTURE_2D,1,e,t,s):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,s,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(r=i.createTexture(),i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const a=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,a),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const o=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,o),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,n,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,r,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,a),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,o),!i.isFramebuffer(o))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:o,renderbuf:a,texture:n,depthTexture:r,width:t,height:s},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,s=null,i=null,n=Uint8Array,r=4){const a=e,o=(this.buffer.height||this.gl.drawingBufferHeight)-1-t,l=new n(r),c=this.gl;return c.readPixels(a,o,1,1,s||c.RGBA,i||c.UNSIGNED_BYTE,l,0),l}readArray(e=null,t=null,s=Uint8Array,i=4){const n=new s(this.buffer.width*this.buffer.height*i),r=this.gl;return r.readPixels(0,0,this.buffer.width,this.buffer.height,e||r.RGBA,t||r.UNSIGNED_BYTE,n,0),n}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),s=t.pixelData,i=t.canvas,n=t.imageData,r=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const a=this.buffer.width,o=this.buffer.height,l=o/2|0,c=4*a,u=new Uint8Array(4*a);for(let e=0;e<l;++e){const t=e*c,i=(o-e-1)*c;u.set(s.subarray(t,t+c)),s.copyWithin(t,i,i+c),s.set(u,i)}return n.data.set(s),r.putImageData(n,0,0),i}readImage(e){const t=this.gl,s=this._getImageDataCache(),i=s.pixelData,n=s.canvas,r=s.imageData,a=s.context;t.readPixels(0,0,this.buffer.width,this.buffer.height,t.RGBA,t.UNSIGNED_BYTE,i),r.data.set(i),a.putImageData(r,0,0);let o=e.format||"png";return"jpeg"!==o&&"png"!==o&&"bmp"!==o&&(console.error("Unsupported image format: '"+o+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),o="png"),n.toDataURL(`image/${o}`)}_getImageDataCache(e=Uint8Array,t=4){const s=this.buffer.width,i=this.buffer.height;let n=this._imageDataCache;if(n&&(n.width===s&&n.height===i||(this._imageDataCache=null,n=null)),!n){const r=document.createElement("canvas"),a=r.getContext("2d");r.width=s,r.height=i,n={pixelData:new e(s*i*t),canvas:r,context:a,imageData:a.createImageData(s,i),width:s,height:i},this._imageDataCache=n}return n.context.resetTransform(),n}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}getTexture(){const e=this;return this._texture||(this._texture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.texture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.texture),!0)},unbind:function(t){e.buffer&&e.buffer.texture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}hasDepthTexture(){return this._hasDepthTexture}getDepthTexture(){if(!this._hasDepthTexture)return null;const e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}destroy(){if(this.allocated){const e=this.gl;e.deleteTexture(this.buffer.texture),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class Ye{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const s=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let i=s[e];return i||(i=new Ke(this.scene.canvas.canvas,this.scene.canvas.gl,t),s[e]=i),i}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Xe(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let s;switch(t){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(t)}return e._cachedExtensions[t]=s,s}var qe=function(){const e=[],t=[],s=[],i=[],n=[];let r=0;const a=new Uint16Array(3),o=new Uint16Array(3),l=new Uint16Array(3),c=h.vec3(),u=h.vec3(),p=h.vec3(),d=h.vec3(),A=h.vec3(),f=h.vec3(),I=h.vec3();return function(m,y,v,w){!function(n,r){const a={};let o,l,c,u;const h=Math.pow(10,4);let p,d,A=0;for(p=0,d=n.length;p<d;p+=3)o=n[p],l=n[p+1],c=n[p+2],u=Math.round(o*h)+"_"+Math.round(l*h)+"_"+Math.round(c*h),void 0===a[u]&&(a[u]=A/3,e[A++]=o,e[A++]=l,e[A++]=c),t[p/3]=a[u];for(p=0,d=r.length;p<d;p++)i[p]=t[r[p]],s[i[p]]=r[p]}(m,y),function(t,s){r=0;for(let m=0,y=t;m<y;m+=3){const t=3*i[m],y=3*i[m+1],v=3*i[m+2];s?(a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],o[0]=e[y],o[1]=e[y+1],o[2]=e[y+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],h.decompressPosition(a,s,c),h.decompressPosition(o,s,u),h.decompressPosition(l,s,p)):(c[0]=e[t],c[1]=e[t+1],c[2]=e[t+2],u[0]=e[y],u[1]=e[y+1],u[2]=e[y+2],p[0]=e[v],p[1]=e[v+1],p[2]=e[v+2]),h.subVec3(p,u,d),h.subVec3(c,u,A),h.cross3Vec3(d,A,f),h.normalizeVec3(f,I);const w=n[r]||(n[r]={normal:h.vec3()});w.normal[0]=I[0],w.normal[1]=I[1],w.normal[2]=I[2],r++}}(y.length,v);const g=[],T=Math.cos(h.DEGTORAD*w),E={};let b,_,D,P,C,R,B,x,S,O,N,L=!1;for(let e=0,t=y.length;e<t;e+=3){const t=e/3;for(let s=0;s<3;s++)b=i[e+s],_=i[e+(s+1)%3],D=Math.min(b,_),P=Math.max(b,_),C=D+","+P,void 0===E[C]?E[C]={index1:D,index2:P,face1:t,face2:void 0}:E[C].face2=t}for(C in E)R=E[C],void 0!==R.face2&&(B=n[R.face1].normal,x=n[R.face2].normal,S=h.dotVec3(B,x),S>T)||(O=s[R.index1],N=s[R.index2],(!L&&O>65535||N>65535)&&(L=!0),g.push(O),g.push(N));return L?new Uint32Array(g):new Uint16Array(g)}}();class Je{constructor(e,t,s,i,n=null,r=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.pickId=this.model.scene._renderer.getPickID(this),this.aabb=h.AABB3(),this._layer=n,this._portionId=r,this._color=[s[0],s[1],s[2],i],this._colorize=[s[0],s[1],s[2],i],this._colorizing=!1,this._transparent=i<255,this.numTriangles=0,this.origin=null}_finalize(e){this._layer.initFlags(this._portionId,e,this._transparent)}_finalize2(){this._layer.flushInitFlags&&this._layer.flushInitFlags()}_setVisible(e){this._layer.setVisible(this._portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this._layer.setColor(this._portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this._layer.setColor(this._portionId,this._colorize,false),this._colorizing=!0):(this._layer.setColor(this._portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const s=e<255,i=this._transparent!==s;this._color[3]=e,this._colorize[3]=e,this._transparent=s,this._colorizing?this._layer.setColor(this._portionId,this._colorize):this._layer.setColor(this._portionId,this._color),i&&this._layer.setTransparent(this._portionId,t,s)}_setOffset(e){this._layer.setOffset(this._portionId,e)}_setHighlighted(e){this._layer.setHighlighted(this._portionId,e,this._transparent)}_setXRayed(e){this._layer.setXRayed(this._portionId,e,this._transparent)}_setSelected(e){this._layer.setSelected(this._portionId,e,this._transparent)}_setEdges(e){this._layer.setEdges(this._portionId,e,this._transparent)}_setClippable(e){this._layer.setClippable(this._portionId,e,this._transparent)}_setCollidable(e){this._layer.setCollidable(this._portionId,e)}_setPickable(e){this._layer.setPickable(this._portionId,e,this._transparent)}_setCulled(e){this._layer.setCulled(this._portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,s,i){return!!this._layer.precisionRayPickSurface&&this._layer.precisionRayPickSurface(this._portionId,e,t,s,i)}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 Ze=0,$e=1,et=2,tt=3,st=4,it=5,nt=6,rt=7,at=8,ot=9,lt=10,ct=11,ut=new e({});class ht{constructor(e){this.id=ut.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ut.removeItem(this.id)}}const pt=function(){const e=h.mat4(),t=h.mat4();return function(s,i){i=i||h.mat4();const n=s[0],r=s[1],a=s[2],o=s[3]-n,l=s[4]-r,c=s[5]-a,u=65535;return h.identityMat4(e),h.translationMat4v(s,e),h.identityMat4(t),h.scalingMat4v([o/u,l/u,c/u],t),h.mulMat4(e,t,i),i}}();var dt=function(){const e=h.mat4(),t=h.mat4();return function(s,i,n){const r=new Uint16Array(s.length),a=new Float32Array([n[0]!==i[0]?65535/(n[0]-i[0]):0,n[1]!==i[1]?65535/(n[1]-i[1]):0,n[2]!==i[2]?65535/(n[2]-i[2]):0]);let o;for(o=0;o<s.length;o+=3)r[o+0]=Math.max(0,Math.min(65535,Math.floor((s[o+0]-i[0])*a[0]))),r[o+1]=Math.max(0,Math.min(65535,Math.floor((s[o+1]-i[1])*a[1]))),r[o+2]=Math.max(0,Math.min(65535,Math.floor((s[o+2]-i[2])*a[2])));h.identityMat4(e),h.translationMat4v(i,e),h.identityMat4(t),h.scalingMat4v([(n[0]-i[0])/65535,(n[1]-i[1])/65535,(n[2]-i[2])/65535],t);return{quantized:r,decodeMatrix:h.mulMat4(e,t,h.identityMat4())}}}();var At=function(){const e=h.mat3(),t=h.mat3();return function(s,i,n){const r=new Uint16Array(s.length),a=new Float32Array([65535/(n[0]-i[0]),65535/(n[1]-i[1])]);let o;for(o=0;o<s.length;o+=2)r[o+0]=Math.max(0,Math.min(65535,Math.floor((s[o+0]-i[0])*a[0]))),r[o+1]=Math.max(0,Math.min(65535,Math.floor((s[o+1]-i[1])*a[1])));h.identityMat3(e),h.translationMat3v(i,e),h.identityMat3(t),h.scalingMat3v([(n[0]-i[0])/65535,(n[1]-i[1])/65535],t);return{quantized:r,decodeMatrix:h.mulMat3(e,t,h.identityMat3())}}}();function ft(e,t,s,i){let n=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),r=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(r))*(n>=0?1:-1),t=(1-Math.abs(n))*(r>=0?1:-1);n=e,r=t}return new Int8Array([Math[s](127.5*n+(n<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function It(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const n=Math.sqrt(t*t+s*s+i*i);return[t/n,s/n,i/n]}function mt(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const yt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,n;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;i<e.length;i+=3)for(n=0;n<3;n++)t[n]=Math.min(t[n],e[i+n]),s[n]=Math.max(s[n],e[i+n]);return{min:t,max:s}},createPositionsDecodeMatrix:pt,compressPositions:dt,compressPosition:function(e,t,s){const i=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);s[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*i[0]))),s[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*i[1]))),s[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*i[2])))},decompressPositions:function(e,t,s=new Float32Array(e.length)){for(let i=0,n=e.length;i<n;i+=3)s[i+0]=e[i+0]*t[0]+t[12],s[i+1]=e[i+1]*t[5]+t[13],s[i+2]=e[i+2]*t[10]+t[14];return s},decompressPosition:function(e,t,s){return s[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14],s},decompressAABB:function(e,t,s=e){return s[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14],s[3]=e[3]*t[0]+t[12],s[4]=e[4]*t[5]+t[13],s[5]=e[5]*t[10]+t[14],s},getUVBounds:function(e){const t=new Float32Array(2),s=new Float32Array(2);let i,n;for(i=0;i<2;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;i<e.length;i+=2)for(n=0;n<2;n++)t[n]=Math.min(t[n],e[i+n]),s[n]=Math.max(s[n],e[i+n]);return{min:t,max:s}},compressUVs:At,decompressUVs:function(e,t,s=new Float32Array(e.length)){for(let i=0,n=e.length;i<n;i+=3)s[i+0]=e[i+0]*t[0]+t[6],s[i+1]=e[i+1]*t[4]+t[7];return s},decompressUV:function(e,t,s){s[0]=e[0]*t[0]+t[6],s[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let s,i,n,r,a;for(let o=0;o<e.length;o+=3)n=s=ft(e,o,"floor","floor"),i=It(s),r=a=mt(e,o,i),s=ft(e,o,"ceil","floor"),i=It(s),r=mt(e,o,i),r>a&&(n=s,a=r),s=ft(e,o,"floor","ceil"),i=It(s),r=mt(e,o,i),r>a&&(n=s,a=r),s=ft(e,o,"ceil","ceil"),i=It(s),r=mt(e,o,i),r>a&&(n=s,a=r),t[o]=n[0],t[o+1]=n[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,n=e.length;s<n;s+=2){let n=e[s+0],r=e[s+1];n=(2*n+1)/255,r=(2*r+1)/255;const a=1-Math.abs(n)-Math.abs(r);a<0&&(n=(1-Math.abs(r))*(n>=0?1:-1),r=(1-Math.abs(n))*(r>=0?1:-1));const o=Math.sqrt(n*n+r*r+a*a);t[i+0]=n/o,t[i+1]=r/o,t[i+2]=a/o,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const n=1-Math.abs(s)-Math.abs(i);n<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const r=Math.sqrt(s*s+i*i+n*n);return t[0]=s/r,t[1]=i/r,t[2]=n/r,t}};class vt extends C{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ht({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.viewport.boundary,t=e[2]/e[3],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),h.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,n){const r=this.scene.canvas.canvas,a=r.offsetWidth/2,o=r.offsetHeight/2;return s[0]=(e[0]-a)/a,s[1]=(e[1]-o)/o,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,i,n),n}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class wt extends C{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ht({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,s=e.viewport.boundary,i=s[2],n=s[3],r=i/n;let a,o,l,c;i>n?(a=-t,o=t,l=t/r,c=-t/r):(a=-t*r,o=t*r,l=t,c=-t),h.orthoMat4c(a,o,c,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,n){const r=this.scene.canvas.canvas,a=r.offsetWidth/2,o=r.offsetHeight/2;return s[0]=(e[0]-a)/a,s[1]=(e[1]-o)/o,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,i,n),n}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class gt extends C{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ht({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){h.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,n){const r=this.scene.canvas.canvas,a=r.offsetWidth/2,o=r.offsetHeight/2;return s[0]=(e[0]-a)/a,s[1]=(e[1]-o)/o,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,i,n),n}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Tt extends C{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ht({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,n){const r=this.scene.canvas.canvas,a=r.offsetWidth/2,o=r.offsetHeight/2;return s[0]=(e[0]-a)/a,s[1]=(e[1]-o)/o,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,i,n),n}destroy(){super.destroy(),this._state.destroy()}}const Et=h.vec3(),bt=h.vec3(),_t=h.vec3(),Dt=h.vec3(),Pt=h.vec3(),Ct=h.vec3(),Rt=h.vec4(),Bt=h.vec4(),xt=h.vec4(),St=h.mat4(),Ot=h.mat4(),Nt=h.vec3(),Lt=h.vec3(),Mt=h.vec3(),Ft=h.vec3();class Ht extends C{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new ht({deviceMatrix:h.mat4(),hasDeviceMatrix:!1,matrix:h.mat4(),normalMatrix:h.mat4(),inverseMatrix:h.mat4()}),this._perspective=new vt(this),this._ortho=new wt(this),this._frustum=new gt(this),this._customProjection=new Tt(this),this._project=this._perspective,this._eye=h.vec3([0,0,10]),this._look=h.vec3([0,0,0]),this._up=h.vec3([0,1,0]),this._worldUp=h.vec3([0,1,0]),this._worldRight=h.vec3([1,0,0]),this._worldForward=h.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(h.subVec3(this._eye,this._look,Nt),h.normalizeVec3(Nt,Lt),h.mulVec3Scalar(Lt,1e3,Mt),h.addVec3(this._look,Mt,Ft),t=Ft):t=this._eye,e.hasDeviceMatrix?(h.lookAtMat4v(t,this._look,this._up,Ot),h.mulMat4(e.deviceMatrix,Ot,e.matrix)):h.lookAtMat4v(t,this._look,this._up,e.matrix),h.inverseMat4(this._state.matrix,this._state.inverseMatrix),h.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=h.subVec3(this._eye,this._look,Et);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,St),t=h.transformPoint3(St,t,bt),this.eye=h.addVec3(this._look,t,_t),this.up=h.transformPoint3(St,this._up,Dt)}orbitPitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._eye,this._look,Et);const s=h.cross3Vec3(h.normalizeVec3(t,bt),h.normalizeVec3(this._up,_t));h.rotationMat4v(.0174532925*e,s,St),t=h.transformPoint3(St,t,Dt),this.up=h.transformPoint3(St,this._up,Pt),this.eye=h.addVec3(t,this._look,Ct)}yaw(e){let t=h.subVec3(this._look,this._eye,Et);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,St),t=h.transformPoint3(St,t,bt),this.look=h.addVec3(t,this._eye,_t),this._gimbalLock&&(this.up=h.transformPoint3(St,this._up,Dt))}pitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._look,this._eye,Et);const s=h.cross3Vec3(h.normalizeVec3(t,bt),h.normalizeVec3(this._up,_t));h.rotationMat4v(.0174532925*e,s,St),this.up=h.transformPoint3(St,this._up,Ct),t=h.transformPoint3(St,t,Dt),this.look=h.addVec3(t,this._eye,Pt)}pan(e){const t=h.subVec3(this._eye,this._look,Et),s=[0,0,0];let i;if(0!==e[0]){const n=h.cross3Vec3(h.normalizeVec3(t,[]),h.normalizeVec3(this._up,bt));i=h.mulVec3Scalar(n,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=h.mulVec3Scalar(h.normalizeVec3(this._up,_t),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=h.mulVec3Scalar(h.normalizeVec3(t,Dt),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=h.addVec3(this._eye,s,Pt),this.look=h.addVec3(this._look,s,Ct)}zoom(e){const t=h.subVec3(this._eye,this._look,Et),s=Math.abs(h.lenVec3(t,bt)),i=Math.abs(s+e);if(i<.5)return;const n=h.normalizeVec3(t,_t);this.eye=h.addVec3(this._look,h.mulVec3Scalar(n,i),Dt)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=h.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return h.lenVec3(h.subVec3(this._look,this._eye,Et))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=Rt,s=Bt,i=xt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,h.mulMat4v4(this.viewMatrix,t,s),h.mulMat4v4(this.projMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const n=this.scene.canvas.canvas,r=n.offsetWidth/2,a=n.offsetHeight/2;return[i[0]*r+r,i[1]*a+a]}destroy(){super.destroy(),this._state.destroy()}}const Ut=h.vec4(),Gt=h.vec3();class Vt{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){const i=this._scene,n=i.camera,r=t.model,a=i.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=n.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s);const p=i._sectionPlanesState.sectionPlanes.length;if(p>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,n=r.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const r=n.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,r?1:0),r){const s=e[t];if(c){const e=W(s.dist,s.dir,c,Gt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uLightAmbient=i.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const n=s.lights;let r;for(let e=0,t=n.length;e<t;e++)switch(r=n[e],r.type){case"dir":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=i.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=i.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=i.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=i.getLocation("lightPos"+e),this._uLightDir[e]=i.getLocation("lightDir"+e),this._uLightAttenuation[e]=i.getLocation("lightAttenuation"+e)}this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=i.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,i=this._program,n=t._lightsState.lights,r=t.camera.project;i.bind(),this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=n.length;e<t;e++){const t=n[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const i=t.sao;if(i.possible){const t=s.drawingBufferWidth,n=s.drawingBufferHeight;Ut[0]=t,Ut[1]=n,Ut[2]=i.blendCutoff,Ut[3]=i.blendFactor,s.uniform4fv(this._uSAOParams,Ut),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>0;let n;const r=[];r.push("#version 300 es"),r.push("// Triangles dataTexture draw vertex shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("precision highp usampler2D;"),r.push("precision highp isampler2D;"),r.push("precision highp sampler2D;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("precision mediump usampler2D;"),r.push("precision mediump isampler2D;"),r.push("precision mediump sampler2D;"),r.push("#endif"),r.push("uniform int renderPass;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),r.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),r.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),r.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),r.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),r.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),r.push("uniform highp sampler2D uTextureCameraMatrices;"),r.push("uniform highp sampler2D uTextureModelMatrices;"),r.push("uniform vec3 uCameraEyeRtc;"),r.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("out float isPerspective;")),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++)n=s.lights[e],"ambient"!==n.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===n.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===n.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===n.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")));i&&(r.push("out vec4 vWorldPosition;"),r.push("flat out uint vFlags2;")),r.push("out vec4 vColor;"),r.push("void main(void) {"),r.push("int polygonIndex = gl_VertexID / 3;"),r.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),r.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),r.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),r.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),r.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),r.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),r.push("if (int(flags.x) != renderPass) {"),r.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),r.push(" return;"),r.push("} else {"),r.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),r.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),r.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),r.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),r.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),r.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),r.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),r.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),r.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),r.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),r.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),r.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),r.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),r.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),r.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),r.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),r.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),r.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),r.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),r.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),r.push("if (color.a == 0u) {"),r.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),r.push(" return;"),r.push("};"),r.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),r.push("vec3 position;"),r.push("position = positions[gl_VertexID % 3];"),r.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),r.push("if (solid != 1u) {"),r.push("if (isPerspectiveMatrix(projMatrix)) {"),r.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),r.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),r.push("position = positions[2 - (gl_VertexID % 3)];"),r.push("viewNormal = -viewNormal;"),r.push("}"),r.push("} else {"),r.push("if (viewNormal.z < 0.0) {"),r.push("position = positions[2 - (gl_VertexID % 3)];"),r.push("viewNormal = -viewNormal;"),r.push("}"),r.push("}"),r.push("}"),r.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),r.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),r.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;");for(let e=0,t=s.lights.length;e<t;e++)if(n=s.lights[e],"ambient"!==n.type){if("dir"===n.type)"view"===n.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===n.type)"view"===n.space?r.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==n.type)continue;"view"===n.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return r.push("vec3 rgb = vec3(color.rgb) / 255.0;"),r.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags2 = flags2.r;")),r.push("gl_Position = clipPos;"),r.push("}"),r.push("}"),r}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const jt=new Float32Array([1,1,1]);h.vec4();const kt=h.vec3();class Qt{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,n=i.camera,r=t.model,a=i.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=n.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s),s===it){const e=i.xrayMaterial._state,t=e.fillColor,s=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===tt){const e=i.highlightMaterial._state,t=e.fillColor,s=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===st){const e=i.selectedMaterial._state,t=e.fillColor,s=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else a.uniform4fv(this._uColor,jt);const p=i._sectionPlanesState.sectionPlanes.length;if(p>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,n=r.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const r=n.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,r?1:0),r){const s=e[t];if(c){const e=W(s.dist,s.dir,c,kt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,i=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.y) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("varying float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("uniform vec4 color;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Wt=h.vec3(),zt=new Float32Array([0,0,0,1]);class Kt{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;if(!this._program&&(this._allocate(t),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),a.uniform1i(this._uRenderPass,s),s===lt){const e=n.xrayMaterial._state,t=e.edgeColor,s=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===at){const e=n.highlightMaterial._state,t=e.edgeColor,s=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===ot){const e=n.selectedMaterial._state,t=e.edgeColor,s=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else a.uniform4fv(this._uColor,zt);a.uniformMatrix4fv(this._uViewMatrix,!1,c?j(r.viewMatrix,c):r.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,i.worldMatrix);const u=n._sectionPlanesState.sectionPlanes.length;if(u>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*u,r=i.renderFlags;for(let t=0;t<u;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,Wt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),a.drawArrays(a.LINES,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),a.drawArrays(a.LINES,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),a.drawArrays(a.LINES,0,o.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets"}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=this._program,i=e.camera.project;if(s.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yt=h.vec3();class Xt{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene;n.camera;const r=n.canvas.gl,a=t._state,o=a.textureState,l=t._state.origin;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&o.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),r.uniform1i(this._uRenderPass,s);const c=n._sectionPlanesState.sectionPlanes.length;if(c>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*c,a=i.renderFlags;for(let t=0;t<c;t++){const i=this._uSectionPlanes[t];if(i){const n=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(i.active,n?1:0),n){const s=e[t];if(l){const e=W(s.dist,s.dir,l,Yt);r.uniform3fv(i.pos,e)}else r.uniform3fv(i.pos,s.pos);r.uniform3fv(i.dir,s.dir)}}}}a.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),r.drawArrays(r.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),r.drawArrays(r.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),r.drawArrays(r.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets"}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=this._program,i=e.camera.project;if(s.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vec4 rgb = vec4(color.rgba);"),s.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const qt=h.vec3();class Jt{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s),n.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const p=n._sectionPlanesState.sectionPlanes.length;if(p>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,r=i.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,qt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("smooth out vec4 vWorldPosition;"),s.push("flat out uvec4 vFlags2;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("uniform bool sectionPlaneActive"+n+";"),i.push("uniform vec3 sectionPlanePos"+n+";"),i.push("uniform vec3 sectionPlaneDir"+n+";")}if(i.push("in vec4 vPickColor;"),i.push("out vec4 outPickColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Zt=h.vec3();class $t{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniform1f(this._uPickZNear,e.pickZNear),a.uniform1f(this._uPickZFar,e.pickZFar),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const p=n._sectionPlanesState.sectionPlanes.length;if(p>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,r=i.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,Zt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPackedVertexId=s.getAttribute("packedVertexId"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("uniform bool sectionPlaneActive"+n+";"),i.push("uniform vec3 sectionPlanePos"+n+";"),i.push("uniform vec3 sectionPlaneDir"+n+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 packDepth(const in float depth) {"),i.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),i.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),i.push(" vec4 res = fract(depth * bitShift);"),i.push(" res -= res.xxyz * bitMask;"),i.push(" return res;"),i.push("}"),i.push("out vec4 outPackedDepth;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const es=h.vec3();function ts(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t}class ss{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;e._origin[0]=c[0],e._origin[1]=c[1],e._origin[2]=c[2];const u=t.aabb,h=2e9,p=[ts(u[3]-u[0])*h,ts(u[4]-u[1])*h,ts(u[5]-u[2])*h];e._coordinateScale[0]=ts(p[0]),e._coordinateScale[1]=ts(p[1]),e._coordinateScale[2]=ts(p[2]),this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let d=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),d=e.pickOrigin||d);const A=[d[0]-c[0],d[1]-c[1],d[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this._u_vectorA,e._vectorA),a.uniform2fv(this._u_invVectorAB,e._invVectorAB),a.uniform1i(this._u_layerNumber,e._layerNumber),a.uniform3fv(this._u_coordinateScaler,p),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniform1f(this._uPickZNear,e.pickZNear),a.uniform1f(this._uPickZFar,e.pickZFar),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const f=n._sectionPlanesState.sectionPlanes.length;if(f>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*f,r=i.renderFlags;for(let t=0;t<f;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,es);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}const I="edge"===e._snapMode?a.LINES:a.POINTS;o.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),a.drawArrays(I,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),a.drawArrays(I,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),a.drawArrays(I,0,o.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPackedVertexId=s.getAttribute("packedVertexId"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this._u_vectorA=s.getLocation("_vectorA"),this._u_invVectorAB=s.getLocation("_invVectorAB"),this._u_layerNumber=s.getLocation("_layerNumber"),this._u_coordinateScaler=s.getLocation("_coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 _vectorA;"),s.push("uniform vec2 _invVectorAB;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - _vectorA.x) * _invVectorAB.x;"),s.push(" float y = (clipPos.y - _vectorA.y) * _invVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vViewPosition = clipPos;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),i.push("uniform int _layerNumber;"),i.push("uniform vec3 _coordinateScaler;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*_coordinateScaler.xyz, _layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}h.vec4();const is=h.vec3();function ns(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t}class rs{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;e._origin[0]=c[0],e._origin[1]=c[1],e._origin[2]=c[2];const u=t.aabb,h=2e9,p=[ns(u[3]-u[0])*h,ns(u[4]-u[1])*h,ns(u[5]-u[2])*h];e._coordinateScale[0]=ns(p[0]),e._coordinateScale[1]=ns(p[1]),e._coordinateScale[2]=ns(p[2]),this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let d=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),d=e.pickOrigin||d);const A=[d[0]-c[0],d[1]-c[1],d[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this._u_vectorA,e._vectorA),a.uniform2fv(this._u_invVectorAB,e._invVectorAB),a.uniform1i(this._u_layerNumber,e._layerNumber),a.uniform3fv(this._u_coordinateScaler,p),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniform1f(this._uPickZNear,e.pickZNear),a.uniform1f(this._uPickZFar,e.pickZFar),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const f=n._sectionPlanesState.sectionPlanes.length;if(f>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*f,r=i.renderFlags;for(let t=0;t<f;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,is);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPackedVertexId=s.getAttribute("packedVertexId"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this._u_vectorA=s.getLocation("_vectorA"),this._u_invVectorAB=s.getLocation("_invVectorAB"),this._u_layerNumber=s.getLocation("_layerNumber"),this._u_coordinateScaler=s.getLocation("_coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture draw vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 _vectorA;"),s.push("uniform vec2 _invVectorAB;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - _vectorA.x) * _invVectorAB.x;"),s.push(" float y = (clipPos.y - _vectorA.y) * _invVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.001;"),s.push("clipPos.xyzw *= tmp;"),s.push("vViewPosition = clipPos;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),i.push("uniform int _layerNumber;"),i.push("uniform vec3 _coordinateScaler;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*_coordinateScaler.xyz, - _layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const as=h.vec3();class os{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s),a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uPickInvisible,e.pickInvisible),n.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const p=n._sectionPlanesState.sectionPlanes.length;if(p>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,r=i.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,as);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick normals vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("normal = -normal;"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("normal = -normal;"),s.push("}"),s.push("}"),s.push("}"),s.push("normal = -normal;"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vWorldNormal = normal.xyz;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.w;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("uniform bool sectionPlaneActive"+n+";"),i.push("uniform vec3 sectionPlanePos"+n+";"),i.push("uniform vec3 sectionPlaneDir"+n+";")}if(i.push("in vec3 vWorldNormal;"),i.push("out vec4 outNormal;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outNormal = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}h.vec3();class ls{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("// Triangles dataTexture occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("varying float isPerspective;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(we.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;")),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("// Triangles dataTexture occlusion fragment shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("varying float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("varying float vFragDepth;")),s){i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("void main(void) {"),s){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)i.push(" if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}h.vec4();const cs=h.vec3();class us{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,n=i.camera,r=t.model,a=i.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=n.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s);const p=i._sectionPlanesState.sectionPlanes.length;if(p>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,n=r.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const r=n.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,r?1:0),r){const s=e[t];if(c){const e=W(s.dist,s.dir,c,cs);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,i=this._program,n=t.camera.project;if(i.bind(),s.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState;e._lightsState;const s=t.sectionPlanes.length>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),s&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),i.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),i.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),i.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),i.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const hs=h.vec3();class ps{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=t._state.origin;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t)),a.uniform1i(this._uRenderPass,s),a.uniformMatrix4fv(this._uViewMatrix,!1,l?j(r.viewMatrix,l):r.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,i.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,i.worldNormalMatrix);const c=n._sectionPlanesState.sectionPlanes.length;if(c>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*c,r=i.renderFlags;for(let t=0;t<c;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(l){const e=W(s.dist,s.dir,l,hs);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aOffset.bindArrayBuffer(o.offsetsBuf),this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor.bindArrayBuffer(o.colorsBuf),this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),o.indicesBuf.bind(),a.drawElements(a.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2&&(this._aFlags2=s.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec3 normal;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 worldNormalMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 viewNormalMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("varying float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec3 vViewNormal;"),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(we.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;")),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("varying float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("varying float vFragDepth;")),s){i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("varying vec3 vViewNormal;"),i.push("vec3 packNormalToRGB( const in vec3 normal ) {"),i.push(" return normalize( normal ) * 0.5 + 0.5;"),i.push("}"),i.push("void main(void) {"),s){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}h.vec3();class ds{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=i.getLocation("zFar")),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),t.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastLightId=null}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("// Batched geometry shadow vertex shader"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec4 vViewPosition;"),s.push("void main(void) {"),s.push(" bool visible = (float(flags.x) > 0.0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("varying vec4 vViewPosition;"),s.push("vec4 encodeFloat( const in float v ) {"),s.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),s.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),s.push(" vec4 comp = fract(v * bitShift);"),s.push(" comp -= comp.xxyz * bitMask;"),s.push(" return comp;"),s.push("}"),s.push("void main(void) {"),t){s.push(" bool clippable = (float(vFlags2.x) > 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i<e.sectionPlanes.length;i++)s.push(" if (sectionPlaneActive"+i+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const As=h.vec4(),fs=h.vec3(),Is={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"};class ms{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){const i=this._scene,n=i.camera,r=t.model,a=i.canvas.gl,o=t._state,l=t._state.origin;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,s),a.uniformMatrix4fv(this._uViewMatrix,!1,l?j(n.viewMatrix,l):n.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,r.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,r.worldNormalMatrix);const c=i._sectionPlanesState.sectionPlanes.length;if(c>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*c,n=r.renderFlags;for(let t=0;t<c;t++){const i=this._uSectionPlanes[t];if(i){const r=n.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,r?1:0),r){const s=e[t];if(l){const e=W(s.dist,s.dir,l,fs);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(o.colorsBuf),this._aMetallicRoughness&&this._aMetallicRoughness.bindArrayBuffer(o.metallicRoughnessBuf),this._aFlags&&this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(o.offsetsBuf),o.indicesBuf.bind(),a.drawElements(a.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uGammaFactor=i.getLocation("gammaFactor"),this._uLightAmbient=i.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const n=s.lights;let r;for(let e=0,t=n.length;e<t;e++)switch(r=n[e],r.type){case"dir":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=i.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=i.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=i.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=i.getLocation("lightPos"+e),this._uLightDir[e]=i.getLocation("lightDir"+e),this._uLightAttenuation[e]=i.getLocation("lightAttenuation"+e)}s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aMetallicRoughness=i.getAttribute("metallicRoughness"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=i.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(e){const t=we.MAX_TEXTURE_UNITS,s=this._scene,i=s.canvas.gl,n=this._program,r=s._lightsState,a=r.lights,o=s.camera.project;n.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,s._lightsState.getAmbientColorAndIntensity());for(let e=0,t=a.length;e<t;e++){const t=a[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}if(r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(n.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.lightMaps.length>0&&r.lightMaps[0].texture&&this._uLightMap&&(n.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._withSAO){const n=s.sao;if(n.possible){const s=i.drawingBufferWidth,r=i.drawingBufferHeight;As[0]=s,As[1]=r,As[2]=n.blendCutoff,As[3]=n.blendFactor,i.uniform4fv(this._uSAOParams,As),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++}}if(s.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&i.uniform1f(this._uGammaFactor,s.gammaFactor)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>0,n=t.clippingCaps,r=[];return r.push("// Triangles dataTexture quality draw vertex shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("uniform int renderPass;"),r.push("attribute vec3 position;"),r.push("attribute vec3 normal;"),r.push("attribute vec4 color;"),r.push("attribute vec2 metallicRoughness;"),r.push("attribute vec4 flags;"),r.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&r.push("attribute vec3 offset;"),r.push("uniform mat4 worldMatrix;"),r.push("uniform mat4 worldNormalMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform mat4 viewNormalMatrix;"),r.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("varying float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("varying float isPerspective;")),r.push("vec3 octDecode(vec2 oct) {"),r.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),r.push(" if (v.z < 0.0) {"),r.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);"),r.push(" }"),r.push(" return normalize(v);"),r.push("}"),r.push("varying vec4 vViewPosition;"),r.push("varying vec3 vViewNormal;"),r.push("varying vec4 vColor;"),r.push("varying vec2 vMetallicRoughness;"),s.lightMaps.length>0&&r.push("varying vec3 vWorldNormal;"),i&&(r.push("varying vec4 vWorldPosition;"),r.push("varying vec4 vFlags2;"),n&&r.push("varying vec4 vClipPosition;")),r.push("void main(void) {"),r.push("if (int(flags.x) != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),r.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),we.SUPPORTED_EXTENSIONS.EXT_frag_depth?r.push("vFragDepth = 1.0 + clipPos.w;"):(r.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),r.push("clipPos.z *= clipPos.w;"))),i&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags2 = flags2;"),n&&r.push("vClipPosition = clipPos;")),r.push("vViewPosition = viewPosition;"),r.push("vViewNormal = viewNormal;"),r.push("vColor = color;"),r.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&r.push("vWorldNormal = worldNormal.xyz;"),r.push("gl_Position = clipPos;"),r.push("}"),r.push("}"),r}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState,n=s.sectionPlanes.length>0,r=s.clippingCaps,a=[];a.push("// Triangles dataTexture quality draw fragment shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(a.push("varying float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("varying float vFragDepth;")),a.push("varying vec4 vViewPosition;"),a.push("varying vec3 vViewNormal;"),a.push("varying vec4 vColor;"),a.push("varying vec2 vMetallicRoughness;"),i.lightMaps.length>0&&a.push("varying vec3 vWorldNormal;"),a.push("uniform mat4 viewMatrix;"),i.reflectionMaps.length>0&&a.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&a.push("uniform samplerCube lightMap;"),a.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),r&&a.push("varying vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("#define PI 3.14159265359"),a.push("#define RECIPROCAL_PI 0.31830988618"),a.push("#define RECIPROCAL_PI2 0.15915494"),a.push("#define EPSILON 1e-6"),a.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),a.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),a.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),a.push("}"),a.push("struct IncidentLight {"),a.push(" vec3 color;"),a.push(" vec3 direction;"),a.push("};"),a.push("struct ReflectedLight {"),a.push(" vec3 diffuse;"),a.push(" vec3 specular;"),a.push("};"),a.push("struct Geometry {"),a.push(" vec3 position;"),a.push(" vec3 viewNormal;"),a.push(" vec3 worldNormal;"),a.push(" vec3 viewEyeDir;"),a.push("};"),a.push("struct Material {"),a.push(" vec3 diffuseColor;"),a.push(" float specularRoughness;"),a.push(" vec3 specularColor;"),a.push(" float shine;"),a.push("};"),a.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),a.push(" float r = ggxRoughness + 0.0001;"),a.push(" return (2.0 / (r * r) - 2.0);"),a.push("}"),a.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),a.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),a.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),a.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),a.push("}"),i.reflectionMaps.length>0&&(a.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),a.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),a.push(" vec3 envMapColor = "+Is[i.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),a.push(" return envMapColor;"),a.push("}")),a.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),a.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),a.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),a.push("}"),a.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),a.push(" float a2 = ( alpha * alpha );"),a.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),a.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),a.push(" return 1.0 / ( gl * gv );"),a.push("}"),a.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),a.push(" float a2 = ( alpha * alpha );"),a.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),a.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),a.push(" return 0.5 / max( gv + gl, EPSILON );"),a.push("}"),a.push("float D_GGX(const in float alpha, const in float dotNH) {"),a.push(" float a2 = ( alpha * alpha );"),a.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),a.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),a.push("}"),a.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),a.push(" float alpha = ( roughness * roughness );"),a.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),a.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),a.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),a.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),a.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),a.push(" vec3 F = F_Schlick( specularColor, dotLH );"),a.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),a.push(" float D = D_GGX( alpha, dotNH );"),a.push(" return F * (G * D);"),a.push("}"),a.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),a.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),a.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),a.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),a.push(" vec4 r = roughness * c0 + c1;"),a.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),a.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),a.push(" return specularColor * AB.x + AB.y;"),a.push("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(a.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(a.push(" vec3 irradiance = "+Is[i.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),a.push(" irradiance *= PI;"),a.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),a.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),i.reflectionMaps.length>0&&(a.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),a.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),a.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),a.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),a.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),a.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),a.push("}")),a.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),a.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),a.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),a.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),a.push("}"),a.push("void main(void) {"),n){a.push(" bool clippable = (float(vFlags2.x) > 0.0);"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");r?(a.push(" if (dist > (0.002 * vClipPosition.w)) {"),a.push(" discard;"),a.push(" }"),a.push(" if (dist > 0.0) { "),a.push(" gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push(" gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push(" return;"),a.push("}")):(a.push(" if (dist > 0.0) { "),a.push(" discard;"),a.push(" }")),a.push("}")}a.push("IncidentLight light;"),a.push("Material material;"),a.push("Geometry geometry;"),a.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),a.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),a.push("float alpha = float(vColor.a) / 255.0;"),a.push("vec3 diffuseColor = rgb;"),a.push("float specularF0 = 1.0;"),a.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),a.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),a.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),a.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),a.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),a.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);"),a.push("geometry.position = vViewPosition.xyz;"),a.push("geometry.viewNormal = -normalize(vViewNormal);"),a.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),i.lightMaps.length>0&&a.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&a.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("light.direction = normalize(lightDir"+e+");"):a.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):a.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?a.push("light.direction = normalize(lightDir"+e+");"):a.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),a.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return a.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular);"),a.push("vec4 fragColor;"),this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push(" fragColor = vec4(outgoingLight.rgb * ambient, alpha);")):a.push(" fragColor = vec4(outgoingLight.rgb, alpha);"),t&&a.push("fragColor = linearToGamma(fragColor, gammaFactor);"),a.push("gl_FragColor = fragColor;"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ys=h.vec3();class vs{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),this._program.bindTexture(this._uTexturePerObjectIdPositionsDecodeMatrix,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerObjectIdPositionsDecodeMatrix),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},1),this._program.bindTexture(this._uTexturePerVertexIdCoordinates,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerVertexIdCoordinates),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},2),this._program.bindTexture(this._uTexturePerObjectIdColorsAndFlags,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerObjectIdColorsAndFlags),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},3),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniformMatrix4fv(this._uWorldMatrix,!1,i.worldMatrix);const c=e.pickViewMatrix||r.viewMatrix,u=l?j(c,l):c;if(a.uniformMatrix4fv(this._uViewMatrix,!1,u),a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const h=n._sectionPlanesState.sectionPlanes.length;if(h>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*h,r=i.renderFlags;for(let t=0;t<h;t++){const i=this._uSectionPlanes[t],n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(l){const e=W(s.dist,s.dir,l,ys);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}o.numIndices8Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdPortionIds8Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdIndices8Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},5),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdPortionIds16Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdIndices16Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},5),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdPortionIds32Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdIndices32Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},5),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPackedVertexId=s.getAttribute("packedVertexId"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds"}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick flat normals vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in uvec3 packedVertexId;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform isampler2D uTexturePerPolygonIdNormals;"),s.push("uniform usampler2D uTexturePerPolygonIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out int vFlags2;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_normal_index = polygonIndex & 4095;"),s.push("int v_normal_index = polygonIndex >> 12;"),s.push("int h_packed_object_id_index = ((polygonIndex >> 3) / 2) & 4095;"),s.push("int v_packed_object_id_index = ((polygonIndex >> 3) / 2) >> 12;"),s.push("ivec3 packedObjectId = ivec3(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).rgb);"),s.push("int objectIndex;"),s.push("if (((polygonIndex >> 3) % 2) == 0) {"),s.push(" objectIndex = (packedObjectId.r << 4) + (packedObjectId.g >> 4);"),s.push("} else {"),s.push(" objectIndex = ((packedObjectId.g & 15) << 8) + packedObjectId.b;"),s.push("}"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("int h_index = polygonIndex & 4095;"),s.push("int v_index = polygonIndex >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position1 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("vec3 position2 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("vec3 position3 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(position3 - position1, position2 - position1));"),s.push("int vertexNumber = gl_VertexID % 3;"),s.push("vec3 position;"),s.push("if (vertexNumber == 0) position = position1;"),s.push("else if (vertexNumber == 1) position = position2;"),s.push("else position = position3;"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags2 = flags2.r;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick flat normals fragment shader"),i.push("#extension GL_OES_standard_derivatives : enable"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in int vFlags2;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("uniform bool sectionPlaneActive"+n+";"),i.push("uniform vec3 sectionPlanePos"+n+";"),i.push("uniform vec3 sectionPlaneDir"+n+";")}if(i.push("out vec4 outNormal;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(" outNormal = vec4((worldNormal * 0.5) + 0.5, 1.0);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ws{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRenderer&&!this._colorQualityRenderer.getValid()&&(this._colorQualityRenderer.destroy(),this._colorQualityRenderer=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._vertexDepthRenderer&&!this._vertexDepthRenderer.getValid()&&(this._vertexDepthRenderer.destroy(),this._vertexDepthRenderer=null),this._vertexDepthZBufferInitializer&&!this._vertexDepthZBufferInitializer.getValid()&&(this._vertexDepthZBufferInitializer.destroy(),this._vertexDepthZBufferInitializer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Vt(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Vt(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRenderer(){return this._colorQualityRenderer||(this._colorQualityRenderer=new ms(this._scene,!1)),this._colorQualityRenderer}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO||(this._colorQualityRendererWithSAO=new ms(this._scene,!0)),this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Qt(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new us(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ps(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Kt(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Xt(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Jt(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new os(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new vs(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new $t(this._scene)),this._pickDepthRenderer}get vertexDepthRenderer(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new ss(this._scene)),this._vertexDepthRenderer}get vertexDepthZBufferInitializer(){return this._vertexDepthZBufferInitializer||(this._vertexDepthZBufferInitializer=new rs(this._scene)),this._vertexDepthZBufferInitializer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ls(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ds(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRenderer&&this._colorQualityRenderer.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._vertexDepthRenderer&&this._vertexDepthRenderer.destroy(),this._vertexDepthZBufferInitializer&&this._vertexDepthZBufferInitializer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const gs={};we.SUPPORTED_EXTENSIONS.OES_element_index_uint;class Ts{constructor(){this.positions=[],this.metallicRoughness=[],this.indices8Bits=[],this.indices16Bits=[],this.indices32Bits=[],this.edgeIndices8Bits=[],this.edgeIndices16Bits=[],this.edgeIndices32Bits=[],this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class s{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class i{constructor(){this.items=[]}}class n{constructor(e,t,s,i,n){this.id=e,this.getTitle=t,this.doAction=s,this.getEnabled=i,this.getShown=n,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class r{constructor(e,t,s){this.id=s&&s.id?s.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let n;if(i)for(const s in i)i.hasOwnProperty(s)&&(n=i[s],this._eventCallDepth++,this._eventCallDepth<300?n.callback.call(n.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let n=this._eventSubs[t];n?this._eventSubsNum[t]++:(n={},this._eventSubs[t]=n,this._eventSubsNum[t]=1);const r=this._subIdMap.addItem();n[r]={callback:s,scope:i||this},this._subIdEvents[r]=t;const a=this._events[t];return void 0!==a&&s.call(i||this,a),r}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,n=this.on(e,(function(e){i.off(n),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}let a=!0,o=a?Float64Array:Float32Array;const l=new o(16),c=new o(16),u=new o(4),h={setDoublePrecisionEnabled(e){a=e,o=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,vec2:e=>new o(e||2),vec3:e=>new o(e||3),vec4:e=>new o(e||4),mat3:e=>new o(e||9),mat3ToMat4:(e,t=new o(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 o(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,s){const i=new o(2);for(let n=0,r=e.length;n<r;n++)h.splitDouble(e[n],i),t[n]=i[0],s[n]=i[1]},splitDouble(e,t){const s=o.from([e])[0],i=e-s;t[0]=s,t[1]=i},createUUID:(()=>{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&n]}${e[n>>8&255]}${e[n>>16&255]}${e[n>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,e)),fmod(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new o(e[0]);for(let s=1;s<e.length;s++)t[0]+=e[s][0],t[1]+=e[s][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],n=e[2],r=t[0],a=t[1],o=t[2];return[i*o-n*a,n*r-s*o,s*a-i*r,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],n=e[1],r=e[2],a=t[0],o=t[1],l=t[2];return s[0]=n*l-r*o,s[1]=r*a-i*l,s[2]=i*o-n*a,s},sqLenVec4:e=>h.dotVec4(e,e),lenVec4:e=>Math.sqrt(h.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>h.dotVec3(e,e),sqLenVec2:e=>h.dotVec2(e,e),lenVec3:e=>Math.sqrt(h.sqLenVec3(e)),distVec3:(()=>{const e=new o(3);return(t,s)=>h.lenVec3(h.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(h.sqLenVec2(e)),distVec2:(()=>{const e=new o(2);return(t,s)=>h.lenVec2(h.subVec2(t,s,e))})(),rcpVec3:(e,t)=>h.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/h.lenVec4(e);return h.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/h.lenVec3(e);return h.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/h.lenVec2(e);return h.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=h.dotVec3(e,t)/Math.sqrt(h.sqLenVec3(e)*h.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new o(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=h.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=h.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=h.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s<i;s++)t[s]=e(t[s]);return t}})(),xyzArrayToObject:e=>({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||h.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>h.m4s(0),setMat4ToOnes:()=>h.m4s(1),diagonalMat4v:e=>new o([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,s,i)=>h.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>h.diagonalMat4c(e,e,e,e),identityMat4:(e=new o(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 o(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>h.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],n=e[1],r=e[2],a=e[3],o=e[4],l=e[5],c=e[6],u=e[7],h=e[8],p=e[9],d=e[10],A=e[11],f=e[12],I=e[13],m=e[14],y=e[15],v=t[0],w=t[1],g=t[2],T=t[3],E=t[4],b=t[5],_=t[6],D=t[7],P=t[8],C=t[9],R=t[10],B=t[11],x=t[12],S=t[13],O=t[14],N=t[15];return s[0]=v*i+w*o+g*h+T*f,s[1]=v*n+w*l+g*p+T*I,s[2]=v*r+w*c+g*d+T*m,s[3]=v*a+w*u+g*A+T*y,s[4]=E*i+b*o+_*h+D*f,s[5]=E*n+b*l+_*p+D*I,s[6]=E*r+b*c+_*d+D*m,s[7]=E*a+b*u+_*A+D*y,s[8]=P*i+C*o+R*h+B*f,s[9]=P*n+C*l+R*p+B*I,s[10]=P*r+C*c+R*d+B*m,s[11]=P*a+C*u+R*A+B*y,s[12]=x*i+S*o+O*h+N*f,s[13]=x*n+S*l+O*p+N*I,s[14]=x*r+S*c+O*d+N*m,s[15]=x*a+S*u+O*A+N*y,s},mulMat3(e,t,s){s||(s=new o(9));const i=e[0],n=e[3],r=e[6],a=e[1],l=e[4],c=e[7],u=e[2],h=e[5],p=e[8],d=t[0],A=t[3],f=t[6],I=t[1],m=t[4],y=t[7],v=t[2],w=t[5],g=t[8];return s[0]=i*d+n*I+r*v,s[3]=i*A+n*m+r*w,s[6]=i*f+n*y+r*g,s[1]=a*d+l*I+c*v,s[4]=a*A+l*m+c*w,s[7]=a*f+l*y+c*g,s[2]=u*d+h*I+p*v,s[5]=u*A+h*m+p*w,s[8]=u*f+h*y+p*g,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=h.vec4()){const i=t[0],n=t[1],r=t[2],a=t[3];return s[0]=e[0]*i+e[4]*n+e[8]*r+e[12]*a,s[1]=e[1]*i+e[5]*n+e[9]*r+e[13]*a,s[2]=e[2]*i+e[6]*n+e[10]*r+e[14]*a,s[3]=e[3]*i+e[7]*n+e[11]*r+e[15]*a,s},transposeMat4(e,t){const s=e[4],i=e[14],n=e[8],r=e[13],a=e[12],o=e[9];if(!t||e===t){const t=e[1],l=e[2],c=e[3],u=e[6],h=e[7],p=e[11];return e[1]=s,e[2]=n,e[3]=a,e[4]=t,e[6]=o,e[7]=r,e[8]=l,e[9]=u,e[11]=i,e[12]=c,e[13]=h,e[14]=p,e}return t[0]=e[0],t[1]=s,t[2]=n,t[3]=a,t[4]=e[1],t[5]=e[5],t[6]=o,t[7]=r,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],n=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,t[7]=n}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],a=e[5],o=e[6],l=e[7],c=e[8],u=e[9],h=e[10],p=e[11],d=e[12],A=e[13],f=e[14],I=e[15];return d*u*o*n-c*A*o*n-d*a*h*n+r*A*h*n+c*a*f*n-r*u*f*n-d*u*i*l+c*A*i*l+d*s*h*l-t*A*h*l-c*s*f*l+t*u*f*l+d*a*i*p-r*A*i*p-d*s*o*p+t*A*o*p+r*s*f*p-t*a*f*p-c*a*i*I+r*u*i*I+c*s*o*I-t*u*o*I-r*s*h*I+t*a*h*I},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],n=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8],h=e[9],p=e[10],d=e[11],A=e[12],f=e[13],I=e[14],m=e[15],y=s*o-i*a,v=s*l-n*a,w=s*c-r*a,g=i*l-n*o,T=i*c-r*o,E=n*c-r*l,b=u*f-h*A,_=u*I-p*A,D=u*m-d*A,P=h*I-p*f,C=h*m-d*f,R=p*m-d*I,B=1/(y*R-v*C+w*P+g*D-T*_+E*b);return t[0]=(o*R-l*C+c*P)*B,t[1]=(-i*R+n*C-r*P)*B,t[2]=(f*E-I*T+m*g)*B,t[3]=(-h*E+p*T-d*g)*B,t[4]=(-a*R+l*D-c*_)*B,t[5]=(s*R-n*D+r*_)*B,t[6]=(-A*E+I*w-m*v)*B,t[7]=(u*E-p*w+d*v)*B,t[8]=(a*C-o*D+c*b)*B,t[9]=(-s*C+i*D-r*b)*B,t[10]=(A*T-f*w+m*y)*B,t[11]=(-u*T+h*w-d*y)*B,t[12]=(-a*P+o*_-l*b)*B,t[13]=(s*P-i*_+n*b)*B,t[14]=(-A*g+f*v-I*y)*B,t[15]=(u*g-h*v+p*y)*B,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||h.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||h.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new o(3);return(t,s,i,n)=>(e[0]=t,e[1]=s,e[2]=i,h.translationMat4v(e,n))})(),translationMat4s:(e,t)=>h.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>h.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const n=i[3];i[0]+=n*e,i[1]+=n*t,i[2]+=n*s;const r=i[7];i[4]+=r*e,i[5]+=r*t,i[6]+=r*s;const a=i[11];i[8]+=a*e,i[9]+=a*t,i[10]+=a*s;const o=i[15];return i[12]+=o*e,i[13]+=o*t,i[14]+=o*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=h.normalizeVec4([t[0],t[1],t[2],0],[]),n=Math.sin(e),r=Math.cos(e),a=1-r,o=i[0],l=i[1],c=i[2];let u,p,d,A,f,I;return u=o*l,p=l*c,d=c*o,A=o*n,f=l*n,I=c*n,(s=s||h.mat4())[0]=a*o*o+r,s[1]=a*u+I,s[2]=a*d-f,s[3]=0,s[4]=a*u-I,s[5]=a*l*l+r,s[6]=a*p+A,s[7]=0,s[8]=a*d+f,s[9]=a*p-A,s[10]=a*c*c+r,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,n)=>h.rotationMat4v(e,[t,s,i],n),scalingMat4v:(e,t=h.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=h.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new o(3);return(t,s,i,n)=>(e[0]=t,e[1]=s,e[2]=i,h.scalingMat4v(e,n))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],n=e[2];return t[0]*=s,t[4]*=i,t[8]*=n,t[1]*=s,t[5]*=i,t[9]*=n,t[2]*=s,t[6]*=i,t[10]*=n,t[3]*=s,t[7]*=i,t[11]*=n,t},scalingMat4s:e=>h.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=h.mat4()){const i=e[0],n=e[1],r=e[2],a=e[3],o=i+i,l=n+n,c=r+r,u=i*o,p=i*l,d=i*c,A=n*l,f=n*c,I=r*c,m=a*o,y=a*l,v=a*c;return s[0]=1-(A+I),s[1]=p+v,s[2]=d-y,s[3]=0,s[4]=p-v,s[5]=1-(u+I),s[6]=f+m,s[7]=0,s[8]=d+y,s[9]=f-m,s[10]=1-(u+A),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=h.vec4()){const i=h.clamp,n=e[0],r=e[4],a=e[8],o=e[1],l=e[5],c=e[9],u=e[2],p=e[6],d=e[10];return"XYZ"===t?(s[1]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-c,d),s[2]=Math.atan2(-r,n)):(s[0]=Math.atan2(p,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[1]=Math.atan2(a,d),s[2]=Math.atan2(o,l)):(s[1]=Math.atan2(-u,n),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(p,-1,1)),Math.abs(p)<.99999?(s[1]=Math.atan2(-u,d),s[2]=Math.atan2(-r,l)):(s[1]=0,s[2]=Math.atan2(o,n))):"ZYX"===t?(s[1]=Math.asin(-i(u,-1,1)),Math.abs(u)<.99999?(s[0]=Math.atan2(p,d),s[2]=Math.atan2(o,n)):(s[0]=0,s[2]=Math.atan2(-r,l))):"YZX"===t?(s[2]=Math.asin(i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(-c,l),s[1]=Math.atan2(-u,n)):(s[0]=0,s[1]=Math.atan2(a,d))):"XZY"===t&&(s[2]=Math.asin(-i(r,-1,1)),Math.abs(r)<.99999?(s[0]=Math.atan2(p,l),s[1]=Math.atan2(a,n)):(s[0]=Math.atan2(-c,d),s[1]=0)),s},composeMat4:(e,t,s,i=h.mat4())=>(h.quaternionToRotationMat4(t,i),h.scaleMat4v(s,i),h.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new o(3),t=new o(16);return function(s,i,n,r){e[0]=s[0],e[1]=s[1],e[2]=s[2];let a=h.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const o=h.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=h.lenVec3(e);h.determinantMat4(s)<0&&(a=-a),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const c=1/a,u=1/o,p=1/l;return t[0]*=c,t[1]*=c,t[2]*=c,t[4]*=u,t[5]*=u,t[6]*=u,t[8]*=p,t[9]*=p,t[10]*=p,h.mat4ToQuaternion(t,n),r[0]=a,r[1]=o,r[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=h.mat4());const n=e[0],r=e[1],a=e[2],o=s[0],l=s[1],c=s[2],u=t[0],p=t[1],d=t[2];if(n===u&&r===p&&a===d)return h.identityMat4();let A,f,I,m,y,v,w,g,T,E;return A=n-u,f=r-p,I=a-d,E=1/Math.sqrt(A*A+f*f+I*I),A*=E,f*=E,I*=E,m=l*I-c*f,y=c*A-o*I,v=o*f-l*A,E=Math.sqrt(m*m+y*y+v*v),E?(E=1/E,m*=E,y*=E,v*=E):(m=0,y=0,v=0),w=f*v-I*y,g=I*m-A*v,T=A*y-f*m,E=Math.sqrt(w*w+g*g+T*T),E?(E=1/E,w*=E,g*=E,T*=E):(w=0,g=0,T=0),i[0]=m,i[1]=w,i[2]=A,i[3]=0,i[4]=y,i[5]=g,i[6]=f,i[7]=0,i[8]=v,i[9]=T,i[10]=I,i[11]=0,i[12]=-(m*n+y*r+v*a),i[13]=-(w*n+g*r+T*a),i[14]=-(A*n+f*r+I*a),i[15]=1,i},lookAtMat4c:(e,t,s,i,n,r,a,o,l)=>h.lookAtMat4v([e,t,s],[i,n,r],[a,o,l],[]),orthoMat4c(e,t,s,i,n,r,a){a||(a=h.mat4());const o=t-e,l=i-s,c=r-n;return a[0]=2/o,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/c,a[11]=0,a[12]=-(e+t)/o,a[13]=-(i+s)/l,a[14]=-(r+n)/c,a[15]=1,a},frustumMat4v(e,t,s){s||(s=h.mat4());const i=[e[0],e[1],e[2],0],n=[t[0],t[1],t[2],0];h.addVec4(n,i,l),h.subVec4(n,i,c);const r=2*i[2],a=c[0],o=c[1],u=c[2];return s[0]=r/a,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=r/o,s[6]=0,s[7]=0,s[8]=l[0]/a,s[9]=l[1]/o,s[10]=-l[2]/u,s[11]=-1,s[12]=0,s[13]=0,s[14]=-r*n[2]/u,s[15]=0,s},frustumMat4(e,t,s,i,n,r,a){a||(a=h.mat4());const o=t-e,l=i-s,c=r-n;return a[0]=2*n/o,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2*n/l,a[6]=0,a[7]=0,a[8]=(t+e)/o,a[9]=(i+s)/l,a[10]=-(r+n)/c,a[11]=-1,a[12]=0,a[13]=0,a[14]=-r*n*2/c,a[15]=0,a},perspectiveMat4(e,t,s,i,n){const r=[],a=[];return r[2]=s,a[2]=i,a[1]=r[2]*Math.tan(e/2),r[1]=-a[1],a[0]=a[1]*t,r[0]=-a[0],h.frustumMat4v(r,a,n)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,s=h.vec3()){const i=t[0],n=t[1],r=t[2];return s[0]=e[0]*i+e[4]*n+e[8]*r+e[12],s[1]=e[1]*i+e[5]*n+e[9]*r+e[13],s[2]=e[2]*i+e[6]*n+e[10]*r+e[14],s},transformPoint4:(e,t,s=h.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],n=t.length;let r,a,o,l;const c=e[0],u=e[1],h=e[2],p=e[3],d=e[4],A=e[5],f=e[6],I=e[7],m=e[8],y=e[9],v=e[10],w=e[11],g=e[12],T=e[13],E=e[14],b=e[15];let _;for(let e=0;e<n;++e)l=t[e],r=l[0],a=l[1],o=l[2],_=i[e]||(i[e]=[0,0,0]),_[0]=c*r+d*a+m*o+g,_[1]=u*r+A*a+y*o+T,_[2]=h*r+f*a+v*o+E,_[3]=p*r+I*a+w*o+b;return i.length=n,i},transformPositions3(e,t,s=t){let i;const n=t.length;let r,a,o;const l=e[0],c=e[1],u=e[2];e[3];const h=e[4],p=e[5],d=e[6];e[7];const A=e[8],f=e[9],I=e[10];e[11];const m=e[12],y=e[13],v=e[14];for(e[15],i=0;i<n;i+=3)r=t[i+0],a=t[i+1],o=t[i+2],s[i+0]=l*r+h*a+A*o+m,s[i+1]=c*r+p*a+f*o+y,s[i+2]=u*r+d*a+I*o+v;return s},transformPositions4(e,t,s=t){let i;const n=t.length;let r,a,o;const l=e[0],c=e[1],u=e[2],h=e[3],p=e[4],d=e[5],A=e[6],f=e[7],I=e[8],m=e[9],y=e[10],v=e[11],w=e[12],g=e[13],T=e[14],E=e[15];for(i=0;i<n;i+=4)r=t[i+0],a=t[i+1],o=t[i+2],s[i+0]=l*r+p*a+I*o+w,s[i+1]=c*r+d*a+m*o+g,s[i+2]=u*r+A*a+y*o+T,s[i+3]=h*r+f*a+v*o+E;return s},transformVec3(e,t,s){const i=t[0],n=t[1],r=t[2];return(s=s||this.vec3())[0]=e[0]*i+e[4]*n+e[8]*r,s[1]=e[1]*i+e[5]*n+e[9]*r,s[2]=e[2]*i+e[6]*n+e[10]*r,s},transformVec4(e,t,s){const i=t[0],n=t[1],r=t[2],a=t[3];return(s=s||h.vec4())[0]=e[0]*i+e[4]*n+e[8]*r+e[12]*a,s[1]=e[1]*i+e[5]*n+e[9]*r+e[13]*a,s[2]=e[2]*i+e[6]*n+e[10]*r+e[14]*a,s[3]=e[3]*i+e[7]*n+e[11]*r+e[15]*a,s},rotateVec2(e,t,s,i=e){const n=Math.cos(s),r=Math.sin(s),a=e[0]-t[0],o=e[1]-t[1];return i[0]=a*n-o*r+t[0],i[1]=a*r+o*n+t[1],e},rotateVec3X(e,t,s,i){const n=[],r=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],r[0]=n[0],r[1]=n[1]*Math.cos(s)-n[2]*Math.sin(s),r[2]=n[1]*Math.sin(s)+n[2]*Math.cos(s),i[0]=r[0]+t[0],i[1]=r[1]+t[1],i[2]=r[2]+t[2],i},rotateVec3Y(e,t,s,i){const n=[],r=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],r[0]=n[2]*Math.sin(s)+n[0]*Math.cos(s),r[1]=n[1],r[2]=n[2]*Math.cos(s)-n[0]*Math.sin(s),i[0]=r[0]+t[0],i[1]=r[1]+t[1],i[2]=r[2]+t[2],i},rotateVec3Z(e,t,s,i){const n=[],r=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],r[0]=n[0]*Math.cos(s)-n[1]*Math.sin(s),r[1]=n[0]*Math.sin(s)+n[1]*Math.cos(s),r[2]=n[2],i[0]=r[0]+t[0],i[1]=r[1]+t[1],i[2]=r[2]+t[2],i},projectVec4(e,t){const s=1/e[3];return(t=t||h.vec2())[0]=e[0]*s,t[1]=e[1]*s,t},unprojectVec3:(()=>{const e=new o(16),t=new o(16),s=new o(16);return function(i,n,r,a){return this.transformVec3(this.mulMat4(this.inverseMat4(n,e),this.inverseMat4(r,t),s),i,a)}})(),lerpVec3(e,t,s,i,n,r){const a=r||h.vec3(),o=(e-t)/(s-t);return a[0]=i[0]+o*(n[0]-i[0]),a[1]=i[1]+o*(n[1]-i[1]),a[2]=i[2]+o*(n[2]-i[2]),a},lerpMat4(e,t,s,i,n,r){const a=r||h.mat4(),o=(e-t)/(s-t);return a[0]=i[0]+o*(n[0]-i[0]),a[1]=i[1]+o*(n[1]-i[1]),a[2]=i[2]+o*(n[2]-i[2]),a[3]=i[3]+o*(n[3]-i[3]),a[4]=i[4]+o*(n[4]-i[4]),a[5]=i[5]+o*(n[5]-i[5]),a[6]=i[6]+o*(n[6]-i[6]),a[7]=i[7]+o*(n[7]-i[7]),a[8]=i[8]+o*(n[8]-i[8]),a[9]=i[9]+o*(n[9]-i[9]),a[10]=i[10]+o*(n[10]-i[10]),a[11]=i[11]+o*(n[11]-i[11]),a[12]=i[12]+o*(n[12]-i[12]),a[13]=i[13]+o*(n[13]-i[13]),a[14]=i[14]+o*(n[14]-i[14]),a[15]=i[15]+o*(n[15]-i[15]),a},flatten(e){const t=[];let s,i,n,r,a;for(s=0,i=e.length;s<i;s++)for(a=e[s],n=0,r=a.length;n<r;n++)t.push(a[n]);return t},identityQuaternion:(e=h.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=h.vec4()){const i=e[0]*h.DEGTORAD/2,n=e[1]*h.DEGTORAD/2,r=e[2]*h.DEGTORAD/2,a=Math.cos(i),o=Math.cos(n),l=Math.cos(r),c=Math.sin(i),u=Math.sin(n),p=Math.sin(r);return"XYZ"===t?(s[0]=c*o*l+a*u*p,s[1]=a*u*l-c*o*p,s[2]=a*o*p+c*u*l,s[3]=a*o*l-c*u*p):"YXZ"===t?(s[0]=c*o*l+a*u*p,s[1]=a*u*l-c*o*p,s[2]=a*o*p-c*u*l,s[3]=a*o*l+c*u*p):"ZXY"===t?(s[0]=c*o*l-a*u*p,s[1]=a*u*l+c*o*p,s[2]=a*o*p+c*u*l,s[3]=a*o*l-c*u*p):"ZYX"===t?(s[0]=c*o*l-a*u*p,s[1]=a*u*l+c*o*p,s[2]=a*o*p-c*u*l,s[3]=a*o*l+c*u*p):"YZX"===t?(s[0]=c*o*l+a*u*p,s[1]=a*u*l+c*o*p,s[2]=a*o*p-c*u*l,s[3]=a*o*l-c*u*p):"XZY"===t&&(s[0]=c*o*l-a*u*p,s[1]=a*u*l-c*o*p,s[2]=a*o*p+c*u*l,s[3]=a*o*l+c*u*p),s},mat4ToQuaternion(e,t=h.vec4()){const s=e[0],i=e[4],n=e[8],r=e[1],a=e[5],o=e[9],l=e[2],c=e[6],u=e[10];let p;const d=s+a+u;return d>0?(p=.5/Math.sqrt(d+1),t[3]=.25/p,t[0]=(c-o)*p,t[1]=(n-l)*p,t[2]=(r-i)*p):s>a&&s>u?(p=2*Math.sqrt(1+s-a-u),t[3]=(c-o)/p,t[0]=.25*p,t[1]=(i+r)/p,t[2]=(n+l)/p):a>u?(p=2*Math.sqrt(1+a-s-u),t[3]=(n-l)/p,t[0]=(i+r)/p,t[1]=.25*p,t[2]=(o+c)/p):(p=2*Math.sqrt(1+u-s-a),t[3]=(r-i)/p,t[0]=(n+l)/p,t[1]=(o+c)/p,t[2]=.25*p),t},vec3PairToQuaternion(e,t,s=h.vec4()){const i=Math.sqrt(h.dotVec3(e,e)*h.dotVec3(t,t));let n=i+h.dotVec3(e,t);return n<1e-8*i?(n=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):h.cross3Vec3(e,t,s),s[3]=n,h.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=h.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new o(16);return(t,s,i)=>(i=i||h.vec3(),h.quaternionToRotationMat4(t,e),h.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=h.vec4()){const i=e[0],n=e[1],r=e[2],a=e[3],o=t[0],l=t[1],c=t[2],u=t[3];return s[0]=a*o+i*u+n*c-r*l,s[1]=a*l+n*u+r*o-i*c,s[2]=a*c+r*u+i*l-n*o,s[3]=a*u-i*o-n*l-r*c,s},vec3ApplyQuaternion(e,t,s=h.vec3()){const i=t[0],n=t[1],r=t[2],a=e[0],o=e[1],l=e[2],c=e[3],u=c*i+o*r-l*n,p=c*n+l*i-a*r,d=c*r+a*n-o*i,A=-a*i-o*n-l*r;return s[0]=u*c+A*-a+p*-l-d*-o,s[1]=p*c+A*-o+d*-a-u*-l,s[2]=d*c+A*-l+u*-o-p*-a,s},quaternionToMat4(e,t){t=h.identityMat4(t);const s=e[0],i=e[1],n=e[2],r=e[3],a=2*s,o=2*i,l=2*n,c=a*r,u=o*r,p=l*r,d=a*s,A=o*s,f=l*s,I=o*i,m=l*i,y=l*n;return t[0]=1-(I+y),t[1]=A+p,t[2]=f-u,t[4]=A-p,t[5]=1-(d+y),t[6]=m+c,t[8]=f+u,t[9]=m-c,t[10]=1-(d+I),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],n=e[2],r=e[3],a=s+s,o=i+i,l=n+n,c=s*a,u=s*o,h=s*l,p=i*o,d=i*l,A=n*l,f=r*a,I=r*o,m=r*l;return t[0]=1-(p+A),t[4]=u-m,t[8]=h+I,t[1]=u+m,t[5]=1-(c+A),t[9]=d-f,t[2]=h-I,t[6]=d+f,t[10]=1-(c+p),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const s=h.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>h.normalizeQuaternion(h.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=h.vec4()){const s=(e=h.normalizeQuaternion(e,u))[3],i=2*Math.acos(s),n=Math.sqrt(1-s*s);return n<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n),t[3]=i,t},AABB3:e=>new o(e||6),AABB2:e=>new o(e||4),OBB3:e=>new o(e||32),OBB2:e=>new o(e||16),Sphere3:(e,t,s,i)=>new o([e,t,s,i]),transformOBB3(e,t,s=t){let i;const n=t.length;let r,a,o;const l=e[0],c=e[1],u=e[2],h=e[3],p=e[4],d=e[5],A=e[6],f=e[7],I=e[8],m=e[9],y=e[10],v=e[11],w=e[12],g=e[13],T=e[14],E=e[15];for(i=0;i<n;i+=4)r=t[i+0],a=t[i+1],o=t[i+2],s[i+0]=l*r+p*a+I*o+w,s[i+1]=c*r+d*a+m*o+g,s[i+2]=u*r+A*a+y*o+T,s[i+3]=h*r+f*a+v*o+E;return s},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:(()=>{const e=new o(3),t=new o(3),s=new o(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],h.subVec3(t,e,s),Math.abs(h.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new o(3),t=new o(3),s=new o(3);return(i,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const r=h.subVec3(t,e,s),a=n[0]-i[0],o=i[3]-n[0],l=n[1]-i[1],c=i[4]-n[1],u=n[2]-i[2],p=i[5]-n[2];return r[0]+=a>o?a:o,r[1]+=l>c?l:c,r[2]+=u>p?u:p,Math.abs(h.lenVec3(r))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||h.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||h.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=h.AABB3())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MAX_DOUBLE,e[3]=h.MIN_DOUBLE,e[4]=h.MIN_DOUBLE,e[5]=h.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=h.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new o(3);return(t,s,i)=>{s=s||h.AABB3();let n,r,a,o=h.MAX_DOUBLE,l=h.MAX_DOUBLE,c=h.MAX_DOUBLE,u=h.MIN_DOUBLE,p=h.MIN_DOUBLE,d=h.MIN_DOUBLE;for(let s=0,A=t.length;s<A;s+=3)i?(e[0]=t[s+0],e[1]=t[s+1],e[2]=t[s+2],h.decompressPosition(e,i,e),n=e[0],r=e[1],a=e[2]):(n=t[s+0],r=t[s+1],a=t[s+2]),n<o&&(o=n),r<l&&(l=r),a<c&&(c=a),n>u&&(u=n),r>p&&(p=r),a>d&&(d=a);return s[0]=o,s[1]=l,s[2]=c,s[3]=u,s[4]=p,s[5]=d,s}})(),OBB3ToAABB3(e,t=h.AABB3()){let s,i,n,r=h.MAX_DOUBLE,a=h.MAX_DOUBLE,o=h.MAX_DOUBLE,l=h.MIN_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t+=4)s=e[t+0],i=e[t+1],n=e[t+2],s<r&&(r=s),i<a&&(a=i),n<o&&(o=n),s>l&&(l=s),i>c&&(c=i),n>u&&(u=n);return t[0]=r,t[1]=a,t[2]=o,t[3]=l,t[4]=c,t[5]=u,t},points3ToAABB3(e,t=h.AABB3()){let s,i,n,r=h.MAX_DOUBLE,a=h.MAX_DOUBLE,o=h.MAX_DOUBLE,l=h.MIN_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t++)s=e[t][0],i=e[t][1],n=e[t][2],s<r&&(r=s),i<a&&(a=i),n<o&&(o=n),s>l&&(l=s),i>c&&(c=i),n>u&&(u=n);return t[0]=r,t[1]=a,t[2]=o,t[3]=l,t[4]=c,t[5]=u,t},points3ToSphere3:(()=>{const e=new o(3);return(t,s)=>{s=s||h.vec4();let i,n=0,r=0,a=0;const o=t.length;for(i=0;i<o;i++)n+=t[i][0],r+=t[i][1],a+=t[i][2];s[0]=n/o,s[1]=r/o,s[2]=a/o;let l,c=0;for(i=0;i<o;i++)l=Math.abs(h.lenVec3(h.subVec3(t[i],s,e))),l>c&&(c=l);return s[3]=c,s}})(),positions3ToSphere3:(()=>{const e=new o(3),t=new o(3);return(s,i)=>{i=i||h.vec4();let n,r=0,a=0,o=0;const l=s.length;let c=0;for(n=0;n<l;n+=3)r+=s[n],a+=s[n+1],o+=s[n+2];const u=l/3;let p;for(i[0]=r/u,i[1]=a/u,i[2]=o/u,n=0;n<l;n+=3)e[0]=s[n],e[1]=s[n+1],e[2]=s[n+2],p=Math.abs(h.lenVec3(h.subVec3(e,i,t))),p>c&&(c=p);return i[3]=c,i}})(),OBB3ToSphere3:(()=>{const e=new o(3),t=new o(3);return(s,i)=>{i=i||h.vec4();let n,r=0,a=0,o=0;const l=s.length,c=l/4;for(n=0;n<l;n+=4)r+=s[n+0],a+=s[n+1],o+=s[n+2];i[0]=r/c,i[1]=a/c,i[2]=o/c;let u,p=0;for(n=0;n<l;n+=4)e[0]=s[n+0],e[1]=s[n+1],e[2]=s[n+2],u=Math.abs(h.lenVec3(h.subVec3(e,i,t))),u>p&&(p=u);return i[3]=p,i}})(),getSphere3Center:(e,t=h.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=h.vec3()){let s=0,i=0,n=0;for(var r=0,a=e.length;r<a;r+=3)s+=e[r+0],i+=e[r+1],n+=e[r+2];const o=e.length/3;return t[0]=s/o,t[1]=i/o,t[2]=n/o,t},expandAABB3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e),expandAABB3Point3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e),expandAABB3Points3(e,t){for(var s,i,n,r=0,a=t.length;r<a;r+=3)s=t[r],i=t[r+1],n=t[r+2],e[0]>s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>n&&(e[2]=n),e[3]<s&&(e[3]=s),e[4]<i&&(e[4]=i),e[5]<n&&(e[5]=n);return e},collapseAABB2:(e=h.AABB2())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MIN_DOUBLE,e[3]=h.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2],planeAABB3Intersect(e,t,s){let i,n;e[0]>0?(i=e[0]*s[0],n=e[0]*s[3]):(i=e[0]*s[3],n=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],n+=e[1]*s[4]):(i+=e[1]*s[4],n+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],n+=e[2]*s[5]):(i+=e[2]*s[5],n+=e[2]*s[2]);if(i<=-t&&n<=-t)return-1;return i>=-t&&n>=-t?1:0},OBB3ToAABB2(e,t=h.AABB2()){let s,i,n,r,a=h.MAX_DOUBLE,o=h.MAX_DOUBLE,l=h.MIN_DOUBLE,c=h.MIN_DOUBLE;for(let t=0,u=e.length;t<u;t+=4)s=e[t+0],i=e[t+1],n=e[t+3]||1,r=1/n,s*=r,i*=r,s<a&&(a=s),i<o&&(o=i),s>l&&(l=s),i>c&&(c=i);return t[0]=a,t[1]=o,t[2]=l,t[3]=c,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e),expandAABB2Point2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e),AABB2ToCanvas(e,t,s,i=e){const n=.5*(e[0]+1),r=.5*(e[1]+1),a=.5*(e[2]+1),o=.5*(e[3]+1);return i[0]=Math.floor(n*t),i[1]=s-Math.floor(o*s),i[2]=Math.floor(a*t),i[3]=s-Math.floor(r*s),i},tangentQuadraticBezier:(e,t,s,i)=>2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,n)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+3*e*e*n,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,s,i,n){const r=.5*(s-e),a=.5*(i-t),o=n*n;return(2*t-2*s+r+a)*(n*o)+(-3*t+3*s-2*r-a)*o+r*n+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,n){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,n)},triangleNormal(e,t,s,i=h.vec3()){const n=t[0]-e[0],r=t[1]-e[1],a=t[2]-e[2],o=s[0]-e[0],l=s[1]-e[1],c=s[2]-e[2],u=r*c-a*l,p=a*o-n*c,d=n*l-r*o,A=Math.sqrt(u*u+p*p+d*d);return 0===A?(i[0]=0,i[1]=0,i[2]=0):(i[0]=u/A,i[1]=p/A,i[2]=d/A),i},rayTriangleIntersect:(()=>{const e=new o(3),t=new o(3),s=new o(3),i=new o(3),n=new o(3);return(r,a,o,l,c,u)=>{u=u||h.vec3();const p=h.subVec3(l,o,e),d=h.subVec3(c,o,t),A=h.cross3Vec3(a,d,s),f=h.dotVec3(p,A);if(f<1e-6)return null;const I=h.subVec3(r,o,i),m=h.dotVec3(I,A);if(m<0||m>f)return null;const y=h.cross3Vec3(I,p,n),v=h.dotVec3(a,y);if(v<0||m+v>f)return null;const w=h.dotVec3(d,y)/f;return u[0]=r[0]+w*a[0],u[1]=r[1]+w*a[1],u[2]=r[2]+w*a[2],u}})(),rayPlaneIntersect:(()=>{const e=new o(3),t=new o(3),s=new o(3),i=new o(3);return(n,r,a,o,l,c)=>{c=c||h.vec3(),r=h.normalizeVec3(r,e);const u=h.subVec3(o,a,t),p=h.subVec3(l,a,s),d=h.cross3Vec3(u,p,i);h.normalizeVec3(d,d);const A=-h.dotVec3(a,d),f=-(h.dotVec3(n,d)+A)/h.dotVec3(r,d);return c[0]=n[0]+f*r[0],c[1]=n[1]+f*r[1],c[2]=n[2]+f*r[2],c}})(),cartesianToBarycentric:(()=>{const e=new o(3),t=new o(3),s=new o(3);return(i,n,r,a,o)=>{const l=h.subVec3(a,n,e),c=h.subVec3(r,n,t),u=h.subVec3(i,n,s),p=h.dotVec3(l,l),d=h.dotVec3(l,c),A=h.dotVec3(l,u),f=h.dotVec3(c,c),I=h.dotVec3(c,u),m=p*f-d*d;if(0===m)return null;const y=1/m,v=(f*A-d*I)*y,w=(p*I-d*A)*y;return o[0]=1-v-w,o[1]=w,o[2]=v,o}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,n=h.vec3()){const r=e[0],a=e[1],o=e[2];return n[0]=t[0]*r+s[0]*a+i[0]*o,n[1]=t[1]*r+s[1]*a+i[1]*o,n[2]=t[2]*r+s[2]*a+i[2]*o,n},mergeVertices(e,t,s,i){const n={},r=[],a=[],o=t?[]:null,l=s?[]:null,c=[];let u,h,p,d;const A=1e4;let f,I,m=0;for(f=0,I=e.length;f<I;f+=3)u=e[f],h=e[f+1],p=e[f+2],d=`${Math.round(u*A)}_${Math.round(h*A)}_${Math.round(p*A)}`,void 0===n[d]&&(n[d]=a.length/3,a.push(u),a.push(h),a.push(p),t&&(o.push(t[f]),o.push(t[f+1]),o.push(t[f+2])),s&&(l.push(s[m]),l.push(s[m+1]))),r[f/3]=n[d],m+=2;for(f=0,I=i.length;f<I;f++)c[f]=r[i[f]];const y={positions:a,indices:c};return o&&(y.normals=o),l&&(y.uv=l),y},buildNormals:(()=>{const e=new o(3),t=new o(3),s=new o(3),i=new o(3),n=new o(3),r=new o(3);return(a,o,l)=>{let c,u;const p=new Array(a.length/3);let d,A,f,I,m,y,v;for(c=0,u=o.length;c<u;c+=3){d=o[c],A=o[c+1],f=o[c+2],e[0]=a[3*d],e[1]=a[3*d+1],e[2]=a[3*d+2],t[0]=a[3*A],t[1]=a[3*A+1],t[2]=a[3*A+2],s[0]=a[3*f],s[1]=a[3*f+1],s[2]=a[3*f+2],h.subVec3(t,e,i),h.subVec3(s,e,n);const l=h.vec3();h.normalizeVec3(h.cross3Vec3(i,n,r),l),p[d]||(p[d]=[]),p[A]||(p[A]=[]),p[f]||(p[f]=[]),p[d].push(l),p[A].push(l),p[f].push(l)}for(l=l&&l.length===a.length?l:new Float32Array(a.length),c=0,u=p.length;c<u;c++){I=p[c].length,m=0,y=0,v=0;for(let e=0;e<I;e++)m+=p[c][e][0],y+=p[c][e][1],v+=p[c][e][2];l[3*c]=m/I,l[3*c+1]=y/I,l[3*c+2]=v/I}return l}})(),buildTangents:(()=>{const e=new o(3),t=new o(3),s=new o(3),i=new o(3),n=new o(3),r=new o(3),a=new o(3);return(o,l,c)=>{const u=new Float32Array(o.length);for(let p=0;p<l.length;p+=3){let d=l[p];const A=o.subarray(3*d,3*d+3),f=c.subarray(2*d,2*d+2);d=l[p+1];const I=o.subarray(3*d,3*d+3),m=c.subarray(2*d,2*d+2);d=l[p+2];const y=o.subarray(3*d,3*d+3),v=c.subarray(2*d,2*d+2),w=h.subVec3(I,A,e),g=h.subVec3(y,A,t),T=h.subVec2(m,f,s),E=h.subVec2(v,f,i),b=1/(T[0]*E[1]-T[1]*E[0]),_=h.mulVec3Scalar(h.subVec3(h.mulVec3Scalar(w,E[1],n),h.mulVec3Scalar(g,T[1],r),a),b,r);let D;for(let e=0;e<3;e++)D=3*l[p+e],u[D]+=_[0],u[D+1]+=_[1],u[D+2]+=_[2]}return u}})(),buildPickTriangles(e,t,s){const i=t.length,n=s?new Uint16Array(9*i):new Float32Array(9*i),r=new Uint8Array(12*i);let a,o,l,c,u,h,p=0,d=0,A=0;for(let s=0;s<i;s+=3)h=p>>24&255,u=p>>16&255,c=p>>8&255,l=255&p,o=t[s],a=3*o,n[d++]=e[a],n[d++]=e[a+1],n[d++]=e[a+2],r[A++]=l,r[A++]=c,r[A++]=u,r[A++]=h,o=t[s+1],a=3*o,n[d++]=e[a],n[d++]=e[a+1],n[d++]=e[a+2],r[A++]=l,r[A++]=c,r[A++]=u,r[A++]=h,o=t[s+2],a=3*o,n[d++]=e[a],n[d++]=e[a+1],n[d++]=e[a+2],r[A++]=l,r[A++]=c,r[A++]=u,r[A++]=h,p++;return{positions:n,colors:r}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,n={},r=[],a={};let o,l,c,u,p;const d=1e4;let A,f,I,m,y,v;for(f=0,m=e.length;f<m;f+=3){A=f/3,l=e[f],c=e[f+1],u=e[f+2],p=`${Math.round(l*d)}_${Math.round(c*d)}_${Math.round(u*d)}`,void 0===n[p]?n[p]=[A]:n[p].push(A);const s=h.normalizeVec3([t[f],t[f+1],t[f+2]]);r[A]=s,o=h.vec4([s[0],s[1],s[2],1]),a[A]=o}for(p in n)if(n.hasOwnProperty(p)){const e=n[p],t=e.length;for(f=0;f<t;f++){const s=e[f];for(o=a[s],I=0;I<t;I++){if(f===I)continue;const t=e[I];y=r[s],v=r[t];Math.abs(h.angleVec3(y,v)/h.DEGTORAD)<i&&(o[0]+=v[0],o[1]+=v[1],o[2]+=v[2],o[3]+=1)}}}for(f=0,m=t.length;f<m;f+=3)o=a[f/3],t[f+0]=o[0]/o[3],t[f+1]=o[1]/o[3],t[f+2]=o[2]/o[3]},transformRay:(()=>{const e=new o(4),t=new o(4);return(s,i,n,r,a)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,h.transformVec4(s,e,t),r[0]=t[0],r[1]=t[1],r[2]=t[2],e[0]=n[0],e[1]=n[1],e[2]=n[2],h.transformVec3(s,e,t),h.normalizeVec3(t),a[0]=t[0],a[1]=t[1],a[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new o(16),t=new o(16),s=new o(4),i=new o(4),n=new o(4),r=new o(4);return(a,o,l,c,u,p)=>{const d=h.mulMat4(l,o,e),A=h.inverseMat4(d,t),f=a.width,I=a.height,m=(c[0]-f/2)/(f/2),y=-(c[1]-I/2)/(I/2);s[0]=m,s[1]=y,s[2]=-1,s[3]=1,h.transformVec4(A,s,i),h.mulVec4Scalar(i,1/i[3]),n[0]=m,n[1]=y,n[2]=1,n[3]=1,h.transformVec4(A,n,r),h.mulVec4Scalar(r,1/r[3]),u[0]=r[0],u[1]=r[1],u[2]=r[2],h.subVec3(r,i,p),h.normalizeVec3(p)}})(),canvasPosToLocalRay:(()=>{const e=new o(3),t=new o(3);return(s,i,n,r,a,o,l)=>{h.canvasPosToWorldRay(s,i,n,a,e,t),h.worldRayToLocalRay(r,e,t,o,l)}})(),worldRayToLocalRay:(()=>{const e=new o(16),t=new o(4),s=new o(4);return(i,n,r,a,o)=>{const l=h.inverseMat4(i,e);t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=1,h.transformVec4(l,t,s),a[0]=s[0],a[1]=s[1],a[2]=s[2],h.transformVec3(l,r,o)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,n,r){const a=new o(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let c,u;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,c=0,u=s.length;c<u;++c){var h=3*s[c];for(let e=0;e<3;++e){const t=3*i[h+e];n[t]<a[0]&&(a[0]=n[t]),n[t]>a[3]&&(a[3]=n[t]),n[t+1]<a[1]&&(a[1]=n[t+1]),n[t+1]>a[4]&&(a[4]=n[t+1]),n[t+2]<a[2]&&(a[2]=n[t+2]),n[t+2]>a[5]&&(a[5]=n[t+2])}}if(s.length<20||r>10)return l.triangles=s,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let p=0;e[1]>e[p]&&(p=1),e[2]>e[p]&&(p=2),l.splitDim=p;const d=(a[p]+a[p+3])/2,A=new Array(s.length);let f=0;const I=new Array(s.length);let m=0;for(c=0,u=s.length;c<u;++c){const e=i[h=3*s[c]],t=3*i[h+1],r=3*i[h+2];n[3*e+p]<=d||n[t+p]<=d||n[r+p]<=d?A[f++]=s[c]:I[m++]=s[c]}return A.length=f,I.length=m,l.left=t(A,i,n,r+1),l.right=t(I,i,n,r+1),l}return(e,s)=>{const i=e.length/3,n=new Array(i);for(let e=0;e<i;++e)n[e]=e;return t(n,e,s,0)}})(),decompressPosition(e,t,s){(s=s||e)[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,s=new Float32Array(e.length)){for(let i=0,n=e.length;i<n;i+=3)s[i+0]=e[i+0]*t[0]+t[12],s[i+1]=e[i+1]*t[5]+t[13],s[i+2]=e[i+2]*t[10]+t[14];return s},decompressUV(e,t,s){s[0]=e[0]*t[0]+t[6],s[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,s=new Float32Array(e.length)){for(let i=0,n=e.length;i<n;i+=3)s[i+0]=e[i+0]*t[0]+t[6],s[i+1]=e[i+1]*t[4]+t[7];return s},octDecodeVec2(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const n=1-Math.abs(s)-Math.abs(i);n<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const r=Math.sqrt(s*s+i*i+n*n);return t[0]=s/r,t[1]=i/r,t[2]=n/r,t},octDecodeVec2s(e,t){for(let s=0,i=0,n=e.length;s<n;s+=2){let n=e[s+0],r=e[s+1];n=(2*n+1)/255,r=(2*r+1)/255;const a=1-Math.abs(n)-Math.abs(r);a<0&&(n=(1-Math.abs(r))*(n>=0?1:-1),r=(1-Math.abs(n))*(r>=0?1:-1));const o=Math.sqrt(n*n+r*r+a*a);t[i+0]=n/o,t[i+1]=r/o,t[i+2]=a/o,i+=3}return t}};h.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],n=[];let r=0;const a=new Uint16Array(3),o=new Uint16Array(3),l=new Uint16Array(3),c=h.vec3(),u=h.vec3(),p=h.vec3(),d=h.vec3(),A=h.vec3(),f=h.vec3(),I=h.vec3();return function(m,y,v,w){!function(n,r){const a={};let o,l,c,u;const h=Math.pow(10,4);let p,d,A=0;for(p=0,d=n.length;p<d;p+=3)o=n[p],l=n[p+1],c=n[p+2],u=Math.round(o*h)+"_"+Math.round(l*h)+"_"+Math.round(c*h),void 0===a[u]&&(a[u]=A/3,e[A++]=o,e[A++]=l,e[A++]=c),t[p/3]=a[u];for(p=0,d=r.length;p<d;p++)i[p]=t[r[p]],s[i[p]]=r[p]}(m,y),function(t,s){r=0;for(let m=0,y=t;m<y;m+=3){const t=3*i[m],y=3*i[m+1],v=3*i[m+2];s?(a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],o[0]=e[y],o[1]=e[y+1],o[2]=e[y+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],h.decompressPosition(a,s,c),h.decompressPosition(o,s,u),h.decompressPosition(l,s,p)):(c[0]=e[t],c[1]=e[t+1],c[2]=e[t+2],u[0]=e[y],u[1]=e[y+1],u[2]=e[y+2],p[0]=e[v],p[1]=e[v+1],p[2]=e[v+2]),h.subVec3(p,u,d),h.subVec3(c,u,A),h.cross3Vec3(d,A,f),h.normalizeVec3(f,I);const w=n[r]||(n[r]={normal:h.vec3()});w.normal[0]=I[0],w.normal[1]=I[1],w.normal[2]=I[2],r++}}(y.length,v);const g=[],T=Math.cos(h.DEGTORAD*w),E={};let b,_,D,P,C,R,B,x,S,O,N,L=!1;for(let e=0,t=y.length;e<t;e+=3){const t=e/3;for(let s=0;s<3;s++)b=i[e+s],_=i[e+(s+1)%3],D=Math.min(b,_),P=Math.max(b,_),C=D+","+P,void 0===E[C]?E[C]={index1:D,index2:P,face1:t,face2:void 0}:E[C].face2=t}for(C in E)R=E[C],void 0!==R.face2&&(B=n[R.face1].normal,x=n[R.face2].normal,S=h.dotVec3(B,x),S>T)||(O=s[R.index1],N=s[R.index2],(!L&&O>65535||N>65535)&&(L=!0),g.push(O),g.push(N));return L?new Uint32Array(g):new Uint16Array(g)}}();class p{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const d={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var A=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],s=e[0].charCodeAt(0),i=s+e[1],n=s;n<i;++n)t.push(n);return String.fromCharCode.apply(null,t)})).join("");function f(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return A.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}const I=function(){for(var e={},t=window.location.search.substring(1).split("&"),s=0;s<t.length;s++){var i=t[s].split("=");if(void 0===e[i[0]])e[i[0]]=decodeURIComponent(i[1]);else if("string"==typeof e[i[0]]){var n=[e[i[0]],decodeURIComponent(i[1])];e[i[0]]=n}else e[i[0]].push(decodeURIComponent(i[1]))}return e}();const m={xmlToJson:function e(t,s){if(t.nodeType===t.TEXT_NODE){var i=t.nodeValue;if(null===i.match(/^\s+$/))return i}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var n={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var r=0;r<t.attributes.length;r++){var a=t.attributes[r];n[s[a.nodeName]||a.nodeName]=a.nodeValue}for(var o=0;o<t.childNodes.length;o++){(r=e(t.childNodes[o],s))&&n.children.push(r)}return n}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return f(t[0],2)+[1,4,7,10,13].map((function(e){return f((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var s=[],i=function(e){e.type===t&&s.push(e),(e.children||[]).forEach((function(e){i(e)}))};return i(e),s},timeout:function(e){return new Promise((function(t,s){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,s){var i=new XMLHttpRequest;i.open(e.method||"GET",e.url,!0),i.onload=function(n){console.log(e.url,i.readyState,i.status),4===i.readyState&&(200===i.status?t(i.responseXML):s(i.statusText))},i.send(null)}))},loadJSON:function(e,t,s){var i=e=>{};t=t||i,s=s||i;var n=new XMLHttpRequest;n.overrideMimeType("application/json"),n.open("GET",e,!0),n.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var n;try{n=JSON.parse(i)}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(n)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),n.addEventListener("error",(function(e){s(e)}),!1),n.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;const n=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(n){const e=!!n[2];var r=n[3];r=window.decodeURIComponent(r),e&&(r=window.atob(r));try{const e=new ArrayBuffer(r.length),s=new Uint8Array(e);for(var a=0;a<r.length;a++)s[a]=r.charCodeAt(a);window.setTimeout((function(){t(e)}),0)}catch(e){window.setTimeout((function(){s(e)}),0)}}else{const i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onreadystatechange=function(){4===i.readyState&&(200===i.status?t(i.response):s("loadArrayBuffer error : "+i.response))},i.send(null)}},queryString:I,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return m.isString(e)||m.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(m.isNumeric(e)||m.isString(e)?`${e}`:e.id)===(m.isNumeric(t)||m.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return m.apply(e,{})},apply:function(e,t){for(const s in e)e.hasOwnProperty(s)&&(t[s]=e[s]);return t},apply2:function(e,t){for(const s in e)e.hasOwnProperty(s)&&void 0!==e[s]&&null!==e[s]&&(t[s]=e[s]);return t},applyIf:function(e,t){for(const s in e)e.hasOwnProperty(s)&&(void 0!==t[s]&&null!==t[s]||(t[s]=e[s]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return m.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const s=new e.constructor(e.length+t.length);return s.set(e),s.set(t,e.length),s},flattenParentChildHierarchy:function(e){var t=[];return function e(s){s.id=s.uuid,delete s.oid,t.push(s);var i=s.children;if(i)for(var n=0,r=i.length;n<r;n++){i[n].parent=s.id,e(i[n])}s.children=[]}(e),t}},y={},v=new e,w=new p,g={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},T=[];let E,b=0,_=0;const D=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(D.scenes[e.id])return void console.error(`[ERROR] Scene ${m.inQuotes(e.id)} already exists`)}else e.id=v.addItem({});D.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;y[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},d.components.scenes++,e.once("destroyed",(()=>{v.removeItem(e.id),delete D.scenes[e.id],delete y[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in D.scenes)D.scenes.hasOwnProperty(t)&&(e=D.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete D.scenes[e.id]))},this.scheduleTask=function(e,t){w.push(e),w.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),n=0;for(;w.length>0&&(e<0||i<e);)t=w.shift(),s=w.shift(),s?t.call(s):t(),i=(new Date).getTime(),n++;return n},this.getNumTasks=function(){return w.length}},P=function(){let e=Date.now();if(E=e-b,b>0&&E>0){var t=1e3/E;_+=t,T.push(t),T.length>=30&&(_-=T.shift()),d.frame.fps=Math.round(_/T.length)}!function(e){const t=D.runTasks(e+10),s=D.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=s,d.frame.tasksBudget=10}(e),function(e){for(var t in g.time=e,D.scenes)if(D.scenes.hasOwnProperty(t)){var s=D.scenes[t];g.sceneId=t,g.startTime=s.startTime,g.deltaTime=null!=g.prevTime?g.time-g.prevTime:0,s.fire("tick",g,!0)}g.prevTime=e}(e),function(){const e=D.scenes,t=!1;let s,i,n,r,a;for(a in e)e.hasOwnProperty(a)&&(s=e[a],i=y[a],i||(i=y[a]={}),n=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==n&&(i.ticksPerOcclusionTest=n,i.renderCountdown=n),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=n),r=s.ticksPerRender,i.ticksPerRender!==r&&(i.ticksPerRender=r,i.renderCountdown=r),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=r))}(),b=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(P):requestAnimationFrame(P)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(P):requestAnimationFrame(P);class C{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 C))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let n;if(i)for(const s in i)i.hasOwnProperty(s)&&(n=i[s],this._eventCallDepth++,this._eventCallDepth<300?n.callback.call(n.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let n=this._eventSubs[t];n?this._eventSubsNum[t]++:(n={},this._eventSubs[t]=n,this._eventSubsNum[t]=1);const r=this._subIdMap.addItem();n[r]={callback:s,scope:i||this},this._subIdEvents[r]=t;const a=this._events[t];return void 0!==a&&s.call(i||this,a),r}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,n=this.on(e,(function(e){i.off(n),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+m.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let s=e.component;const i=e.sceneDefault,n=e.sceneSingleton,r=e.type,a=e.on,o=!1!==e.recompiles;if(s&&(m.isNumeric(s)||m.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+m.inQuotes(e))}if(!s)if(!0===n){const e=this.scene.types[r];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+m.inQuotes(s.id));if(r&&!s.isType(r))return void this.error("Expected a "+r+" type or subtype: "+s.type+" "+m.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let c,u,h;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(c=e.subs,u=0,h=c.length;u<h;u++)l.off(c[u]);delete this._attached[t],delete this._attachments[l.id];const i=e.params.onDetached;i&&(m.isFunction(i)?i(l):i.scope?i.callback.call(i.scope,l):i.callback(l)),e.managingLifecycle&&l.destroy()}if(s){const i={params:e,component:s,subs:[],managingLifecycle:false};i.subs.push(s.once("destroyed",(function(){i.params.component=null,this._attach(i.params)}),this)),o&&i.subs.push(s.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=s,this._attachments[s.id]=i;const n=e.onAttached;if(n&&(m.isFunction(n)?n(s):n.scope?n.callback.call(n.scope,s):n.callback(s)),a){let e,t,n,r;for(e in a)if(a.hasOwnProperty(e)){if(t=a[e],m.isFunction(t)?(n=t,r=null):(n=t.callback,r=t.scope),!n)continue;i.subs.push(s.on(e,n,r))}}}return o&&this.fire("dirty",this),this.fire(t,s),s}_checkComponent(e,t){if(!t.isComponent){if(!m.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}_checkComponent2(e,t){if(!t.isComponent){if(!m.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(t.scene.id===this.scene.id){for(var s=0,i=e.length;s<i;s++)if(e[s]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}_own(e){this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(()=>{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():D.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,s,i,n,r;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],s=t.component,i=t.subs,n=0,r=i.length;n<r;n++)s.off(i[n]);t.managingLifecycle&&s.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(s=this._ownedComponents[e],s.destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}const R=1,B=4,x=8,S=16,O=32,N=256,L=512,M=1024,F=2048,H=new Float32Array([0,0,0]),U=new Uint16Array([0,0,0]);class G{constructor(e,t,s,i,n,r){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=i,this._numTriangles=0;for(var a=0,o=this.meshes.length;a<o;a++){const e=this.meshes[a];e.parent=this,this._numTriangles+=e.numTriangles}this.id=s,this.originalSystemId=h.unglobalizeObjectId(e.id,s),this._flags=n,this._aabb=r,this._offsetAABB=h.AABB3(r),this._offset=h.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&e.scene._registerObject(this)}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get aabb(){return this._offsetAABB}get numTriangles(){return this._numTriangles}get visible(){return this._getFlag(R)}set visible(e){if(!!(this._flags&R)!==e){this._flags=e?this._flags|R:this._flags&~R;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this,e),this.model.glRedraw()}}get highlighted(){return this._getFlag(L)}set highlighted(e){if(!!(this._flags&L)!==e){this._flags=e?this._flags|L:this._flags&~L;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this,e),this.model.glRedraw()}}get xrayed(){return this._getFlag(N)}set xrayed(e){if(!!(this._flags&N)!==e){this._flags=e?this._flags|N:this._flags&~N;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this,e),this.model.glRedraw()}}get selected(){return this._getFlag(M)}set selected(e){if(!!(this._flags&M)!==e){this._flags=e?this._flags|M:this._flags&~M;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this,e),this.model.glRedraw()}}get edges(){return this._getFlag(F)}set edges(e){if(!!(this._flags&F)!==e){this._flags=e?this._flags|F:this._flags&~F;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get culledVFC(){return!!this._culledVFC}set culledVFC(e){this._culledVFC=e,this.internalSetCulled()}get culledLOD(){return!!this._culledLOD}set culledLOD(e){this._culledLOD=e,this.internalSetCulled()}get culled(){return!!this._culled}set culled(e){this._culled=e,this.internalSetCulled()}internalSetCulled(){let e=!!this._culled||!!this._culledLOD||!!this._culledVFC;if(!!(this._flags&B)!==e){this._flags=e?this._flags|B:this._flags&~B;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(S)}set clippable(e){if(!!(this._flags&S)!==e){this._flags=e?this._flags|S:this._flags&~S;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(O)}set collidable(e){if(!!(this._flags&O)!==e){this._flags=e?this._flags|O:this._flags&~O;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(x)}set pickable(e){if(!!(this._flags&x)!==e){this._flags=e?this._flags|x:this._flags&~x;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return H[0]=e[0]/255,H[1]=e[1]/255,H[2]=e[2]/255,H}set colorize(e){if(e){U[0]=Math.floor(255*e[0]),U[1]=Math.floor(255*e[1]),U[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(U)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t),this._colorizeUpdated=t}this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(i,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}get offset(){return this._offset}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._offsetAABB[0]=this._aabb[0]+this._offset[0],this._offsetAABB[1]=this._aabb[1]+this._offset[1],this._offsetAABB[2]=this._aabb[2]+this._offset[2],this._offsetAABB[3]=this._aabb[3]+this._offset[0],this._offsetAABB[4]=this._aabb[4]+this._offset[1],this._offsetAABB[5]=this._aabb[5]+this._offset[2],this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e.some((e=>0!==e))),this.model._aabbDirty=!0,this.model.glRedraw()}get castsShadow(){return!1}set castsShadow(e){}get receivesShadow(){return!1}set receivesShadow(e){}get saoEnabled(){return this.model.saoEnabled}getEachVertex(e){for(let t=0,s=this.meshes.length;t<s;t++)this.meshes[t].getEachVertex(e)}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this,!0),this.highlighted&&e._objectHighlightedUpdated(this,!0),this.xrayed&&e._objectXRayedUpdated(this,!0),this.selected&&e._objectSelectedUpdated(this,!0));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_finalize2(){for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1,!1),this.xrayed&&e._objectXRayedUpdated(this,!1),this.selected&&e._objectSelectedUpdated(this,!1),this.highlighted&&e._objectHighlightedUpdated(this,!1),this._opacityUpdated&&(this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1)),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const V=h.vec3(),j=function(){const e=new Float64Array(16),t=new Float64Array(4),s=new Float64Array(4);return function(i,n,r){return r=r||e,t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=1,h.transformVec4(i,t,s),h.setMat4Translation(i,s,r),r.slice()}}();function k(e,t,s){const i=Float32Array.from([e[0]])[0],n=e[0]-i,r=Float32Array.from([e[1]])[0],a=e[1]-r,o=Float32Array.from([e[2]])[0],l=e[2]-o;t[0]=i,t[1]=r,t[2]=o,s[0]=n,s[1]=a,s[2]=l}function Q(e,t,s,i=1e3){const n=h.getPositionsCenter(e,V),r=Math.round(n[0]/i)*i,a=Math.round(n[1]/i)*i,o=Math.round(n[2]/i)*i;s[0]=r,s[1]=a,s[2]=o;const l=0!==s[0]||0!==s[1]||0!==s[2];if(l)for(let s=0,i=e.length;s<i;s+=3)t[s+0]=e[s+0]-r,t[s+1]=e[s+1]-a,t[s+2]=e[s+2]-o;return l}function W(e,t,s,i){const n=h.dotVec3(t,s)+e,r=h.normalizeVec3(t,V);return h.mulVec3Scalar(r,-n,i),i}const z=1,K=4,Y=8,X=16,q=32,J=256,Z=512,$=1024,ee=2048,te=new Float32Array([0,0,0]),se=new Uint16Array([0,0,0]);class ie{constructor(e,t,s,i,n,r){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=i,this._numTriangles=0;for(var a=0,o=this.meshes.length;a<o;a++){const e=this.meshes[a];e.parent=this,this._numTriangles+=e.numTriangles}this.id=s,this.originalSystemId=h.unglobalizeObjectId(e.id,s),this._flags=n,this._aabb=r,this._offsetAABB=h.AABB3(r),this._offset=h.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&e.scene._registerObject(this)}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get aabb(){return this._offsetAABB}get numTriangles(){return this._numTriangles}get visible(){return this._getFlag(z)}set visible(e){if(!!(this._flags&z)!==e){this._flags=e?this._flags|z:this._flags&~z;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this,e),this.model.glRedraw()}}get highlighted(){return this._getFlag(Z)}set highlighted(e){if(!!(this._flags&Z)!==e){this._flags=e?this._flags|Z:this._flags&~Z;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this,e),this.model.glRedraw()}}get xrayed(){return this._getFlag(J)}set xrayed(e){if(!!(this._flags&J)!==e){this._flags=e?this._flags|J:this._flags&~J;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this,e),this.model.glRedraw()}}get selected(){return this._getFlag($)}set selected(e){if(!!(this._flags&$)!==e){this._flags=e?this._flags|$:this._flags&~$;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this,e),this.model.glRedraw()}}get edges(){return this._getFlag(ee)}set edges(e){if(!!(this._flags&ee)!==e){this._flags=e?this._flags|ee:this._flags&~ee;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get culledVFC(){return!!this._culledVFC}set culledVFC(e){this._culledVFC=e,this.internalSetCulled()}get culledLOD(){return!!this._culledLOD}set culledLOD(e){this._culledLOD=e,this.internalSetCulled()}get culled(){return!!this._culled}set culled(e){this._culled=e,this.internalSetCulled()}internalSetCulled(){let e=!!this._culled||!!this._culledLOD||!!this._culledVFC;if(!!(this._flags&K)!==e){this._flags=e?this._flags|K:this._flags&~K;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(X)}set clippable(e){if(!!(this._flags&X)!==e){this._flags=e?this._flags|X:this._flags&~X;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(q)}set collidable(e){if(!!(this._flags&q)!==e){this._flags=e?this._flags|q:this._flags&~q;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(Y)}set pickable(e){if(!!(this._flags&Y)!==e){this._flags=e?this._flags|Y:this._flags&~Y;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return te[0]=e[0]/255,te[1]=e[1]/255,te[2]=e[2]/255,te}set colorize(e){if(e){se[0]=Math.floor(255*e[0]),se[1]=Math.floor(255*e[1]),se[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(se)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t),this._colorizeUpdated=t}this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(i,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}get offset(){return this._offset}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._offsetAABB[0]=this._aabb[0]+this._offset[0],this._offsetAABB[1]=this._aabb[1]+this._offset[1],this._offsetAABB[2]=this._aabb[2]+this._offset[2],this._offsetAABB[3]=this._aabb[3]+this._offset[0],this._offsetAABB[4]=this._aabb[4]+this._offset[1],this._offsetAABB[5]=this._aabb[5]+this._offset[2],this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model._aabbDirty=!0,this.model.glRedraw()}get castsShadow(){return!1}set castsShadow(e){}get receivesShadow(){return!1}set receivesShadow(e){}get saoEnabled(){return this.model.saoEnabled}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this,!0),this.highlighted&&e._objectHighlightedUpdated(this,!0),this.xrayed&&e._objectXRayedUpdated(this,!0),this.selected&&e._objectSelectedUpdated(this,!0));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_finalize2(){for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1,!1),this.xrayed&&e._objectXRayedUpdated(this,!1),this.selected&&e._objectSelectedUpdated(this,!1),this.highlighted&&e._objectHighlightedUpdated(this,!1),this._opacityUpdated&&(this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1)),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const ne=h.vec4(),re=h.vec4();class ae extends C{constructor(e,t){super(e,t),this._entity=null,this._visible=null,this._worldPos=h.vec3(),this._origin=h.vec3(),this._rtcPos=h.vec3(),this._viewPos=h.vec3(),this._canvasPos=h.vec2(),this._occludable=!1,this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(h.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){ne.set(this._viewPos),ne[3]=1,h.transformPoint4(this.scene.camera.projMatrix,ne,re);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+re[0]/re[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-re[1]/re[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof G||this._entity instanceof ie?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),k(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class oe{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var n=this._wireClickable,r=n.style;r.border="solid "+this._thicknessClickable+"px "+this._color,r.position="absolute",r["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,r.width="0px",r.height="0px",r.visibility="visible",r.top="0px",r.left="0px",r["-webkit-transform-origin"]="0 0",r["-moz-transform-origin"]="0 0",r["-ms-transform-origin"]="0 0",r["-o-transform-origin"]="0 0",r["transform-origin"]="0 0",r["-webkit-transform"]="rotate(0deg)",r["-moz-transform"]="rotate(0deg)",r["-ms-transform"]="rotate(0deg)",r["-o-transform"]="rotate(0deg)",r.transform="rotate(0deg)",r.opacity=0,r["pointer-events"]="none",t.onContextMenu,e.appendChild(n),t.onMouseOver&&n.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&n.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&n.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&n.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get _visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){e=!!e,this._visible!==e&&(this._wire.style.visibility=e?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class le{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable";var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var n=this._dotClickable,r=n.style;r["border-radius"]="35px",r.border="solid 10px white",r.position="absolute",r["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,r.width="8px",r.height="8px",r.visibility="visible",r.top="0px",r.left="0px",r.opacity=0,r["pointer-events"]="none",t.onContextMenu,e.appendChild(n),t.onMouseOver&&n.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&n.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&n.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&n.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ce{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var n=e+.5*(s-e),r=t+.5*(i-t),a=this._label.style;a.left=Math.round(n)-20+"px",a.top=Math.round(r)-12+"px"}setPosBetweenWires(e,t,s,i,n,r){var a=(e+s+n)/3,o=(t+i+r)/3,l=this._label.style;l.left=Math.round(a)-20+"px",l.top=Math.round(o)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var ue=h.vec3(),he=h.vec3();class pe extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new ae(s,t.origin),this._cornerMarker=new ae(s,t.corner),this._targetMarker=new ae(s,t.target),this._originWorld=h.vec3(),this._cornerWorld=h.vec3(),this._targetWorld=h.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,n=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,r=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._cornerDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._targetDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._originWire=new oe(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._targetWire=new oe(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._angleLabel=new ce(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:n,onMouseWheel:a,onContextMenu:r}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(h.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._cpDirty){const d=-.3,A=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],I=this._targetMarker.viewPos[2];if(A>d||f>d||I>d)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);h.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var n=i.top-m.top,r=i.left-m.left,a=e.canvas.boundary,o=a[2],l=a[3],c=0,u=0,p=t.length;u<p;u+=4)s[c]=r+Math.floor((1+t[u+0]/t[u+3])*o/2),s[c+1]=n+Math.floor((1-t[u+1]/t[u+3])*l/2),c+=2;if(this._originDot.setPos(s[0],s[1]),this._cornerDot.setPos(s[2],s[3]),this._targetDot.setPos(s[4],s[5]),this._originWire.setStartAndEnd(s[0],s[1],s[2],s[3]),this._targetWire.setStartAndEnd(s[2],s[3],s[4],s[5]),this._angleLabel.setPosBetweenWires(s[0],s[1],s[2],s[3],s[4],s[5]),h.subVec3(this._originWorld,this._cornerWorld,ue),h.subVec3(this._targetWorld,this._cornerWorld,he),!(0===ue[0]&&0===ue[1]&&0===ue[2]||0===he[0]&&0===he[1]&&0===he[2])){const e=this._approximate?" ~ ":" = ";h.normalizeVec3(ue),h.normalizeVec3(he);const t=Math.abs(h.angleVec3(ue,he));this._angle=t/h.DEGTORAD,this._angleLabel.setText(e+this._angle.toFixed(2)+"°")}else this._angleLabel.setText("");this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setCulled(!(this._visible&&this._angleVisible&&this.labelsVisible)),this._cpDirty=!1}}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get corner(){return this._cornerMarker}get target(){return this._targetMarker}get angle(){return this._update(),this._angle}get color(){return this._color}set color(e){this._originDot.setFillColor(e),this._cornerDot.setFillColor(e),this._targetDot.setFillColor(e),this._originWire.setColor(e||"blue"),this._targetWire.setColor(e||"red"),this._angleLabel.setFillColor(e||"#00BBFF"),this._color=e}set visible(e){e=!1!==e,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=!1!==e,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cpDirty=!0,this._needUpdate()}get originVisible(){return this._originVisible}set cornerVisible(e){e=!1!==e,this._cornerVisible=e,this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._cpDirty=!0,this._needUpdate()}get cornerVisible(){return this._cornerVisible}set targetVisible(e){e=!1!==e,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible),this._cpDirty=!0,this._needUpdate()}get targetVisible(){return this._targetVisible}set originWireVisible(e){e=!1!==e,this._originWireVisible=e,this._originWire.setVisible(this._visible&&this._originWireVisible),this._cpDirty=!0,this._needUpdate()}get originWireVisible(){return this._originWireVisible}set targetWireVisible(e){e=!1!==e,this._targetWireVisible=e,this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._cpDirty=!0,this._needUpdate()}get targetWireVisible(){return this._targetWireVisible}set angleVisible(e){e=!1!==e,this._angleVisible=e,this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}get angleVisible(){return this._angleVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._angleLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._cornerDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._originWire.setHighlighted(e),this._targetWire.setHighlighted(e),this._angleLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._cornerDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._originWire.setClickable(this._clickable),this._targetWire.setClickable(this._clickable),this._angleLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._originDot.destroy(),this._cornerDot.destroy(),this._targetDot.destroy(),this._originWire.destroy(),this._targetWire.destroy(),this._angleLabel.destroy(),super.destroy()}}class de extends C{constructor(e){super(e.viewer.scene),this.plugin=e,this._active=!1,this._state=0,this._currentAngleMeasurement=null,this._onMouseHoverSurface=null,this._onHoverNothing=null,this._onMouseHoverOff=null,this._onPickedNothing=null,this._onPickedSurface=null,this._onInputMouseDown=null,this._onInputMouseUp=null,this._onCanvasTouchStart=null,this._onCanvasTouchEnd=null}get active(){return this._active}activate(){if(this._active)return;const e=this.plugin,t=this.scene,s=e.viewer.cameraControl,i=t.canvas.canvas,n=t.input,r=t.pickSurfacePrecisionEnabled;let a=!1,o=null,l=h.vec3();const c=h.vec2();let u,p;const d=h.vec2(),A=h.vec2();h.vec3(),this._onMouseHoverSurface=s.on("hoverSurface",(e=>{if(a=!0,o=e.entity,l.set(e.worldPos),c.set(e.canvasPos),this._currentAngleMeasurement)switch(this._state){case 1:this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.entity=e.entity,this._currentAngleMeasurement.corner.worldPos=e.worldPos,i.style.cursor="pointer";break;case 2:this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.entity=e.entity,this._currentAngleMeasurement.target.worldPos=e.worldPos,i.style.cursor="pointer"}})),this._onInputMouseDown=n.on("mousedown",(e=>{u=e[0],p=e[1]})),this._onInputMouseUp=n.on("mouseup",(e=>{if(!(e[0]>u+5||e[0]<u-5||e[1]>p+5||e[1]<p-5))switch(this._state){case 0:if(a){if(r){const e=t.pick({canvasPos:c,pickSurface:!0,pickSurfacePrecision:r});e&&e.worldPos&&worldPos.set(e.worldPos)}this._currentAngleMeasurement=this.plugin.createMeasurement({id:h.createUUID(),origin:{entity:o,worldPos:l},corner:{entity:o,worldPos:l},target:{entity:o,worldPos:l},approximate:!0}),this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.angleVisible=!1,this._state=1,this.fire("measurementStart",this._currentAngleMeasurement)}break;case 1:if(a){if(r){const e=t.pick({canvasPos:c,pickSurface:!0,pickSurfacePrecision:!0});e&&e.worldPos&&(this._currentAngleMeasurement.corner.worldPos=e.worldPos)}this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._state=2}else this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._state=0,this.fire("measurementCancel",this._currentAngleMeasurement));break;case 2:if(a){if(r){const e=t.pick({canvasPos:c,pickSurface:!0,pickSurfacePrecision:!0});e&&e.worldPos&&(this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.approximate=!1)}this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this.fire("measurementEnd",this._currentAngleMeasurement),this._currentAngleMeasurement=null,this._state=0}else this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._state=0,this.fire("measurementCancel",this._currentAngleMeasurement))}})),this._onHoverNothing=s.on("hoverOff",(e=>{if(a=!1,this._currentAngleMeasurement){switch(this._state){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}i.style.cursor="default"}})),i.addEventListener("touchstart",this._onCanvasTouchStart=e=>{const t=e.touches,s=e.changedTouches;1===t.length&&1===s.length&&Ae(t[0],d)},{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=e=>{const s=e.touches,i=e.changedTouches;if(0===s.length&&1===i.length){if(Ae(i[0],A),A[0]>d[0]+5||A[0]<d[0]-5||A[1]>d[1]+5||A[1]<d[1]-5)return;const e=t.pick({canvasPos:A,pickSurface:!0,pickSurfacePrecision:!1});if(e&&e.worldPos)switch(this._state){case 0:this._currentAngleMeasurement=this.plugin.createMeasurement({id:h.createUUID(),origin:{entity:e.entity,worldPos:e.worldPos},corner:{entity:e.entity,worldPos:e.worldPos},target:{entity:e.entity,worldPos:e.worldPos},approximate:!0}),this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.clickable=!1,this._state=1,this.fire("measurementStart",this._currentAngleMeasurement);break;case 1:this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._state=2;break;case 2:this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.clickable=!0,this.fire("measurementEnd",this._currentAngleMeasurement),this._currentAngleMeasurement=null,this._state=0}else this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._state=0,this.fire("measurementCancel",this._currentAngleMeasurement))}},{passive:!0}),this._active=!0}deactivate(){if(!this._active)return;this.reset();const e=this.plugin.viewer.scene.input,t=this.plugin.viewer.cameraControl,s=this.plugin.viewer.scene.canvas.canvas;e.off(this._onInputMouseDown),e.off(this._onInputMouseUp),t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),s.removeEventListener("touchstart",this._onCanvasTouchStart),s.removeEventListener("touchend",this._onCanvasTouchEnd),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._state=0)}destroy(){this.deactivate(),super.destroy()}}const Ae=function(e,t){if(e){let s=e.target,i=0,n=0;for(;s.offsetParent;)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-i,t[1]=e.pageY-n}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class fe extends ae{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"<p></p>";m.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e);const t=document.createRange().createContextualFragment(e);this._marker=t.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(()=>{this.plugin.fire("markerClicked",this)})),this._marker.addEventListener("mouseenter",(()=>{this.plugin.fire("markerMouseEnter",this)})),this._marker.addEventListener("mouseleave",(()=>{this.plugin.fire("markerMouseLeave",this)})),this._marker.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);let e=this._labelHTML||"<p></p>";m.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e);const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=this.scene.canvas.boundary,t=e[0],s=e[1],i=this.canvasPos;this._marker.style.left=Math.floor(t+i[0])-12+"px",this._marker.style.top=Math.floor(s+i[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+i[0]+20)+"px",this._label.style.top=Math.floor(s+i[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const s=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),s)}return e}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const s=e[t];this.setField(t,s)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):this._marker.parentNode.removeChild(this._marker)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}const Ie=h.vec3(),me=h.vec3(),ye=h.vec3();class ve extends C{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const s=this._element;s&&(s.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const we={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},ge=document.createElement("canvas");if(ge){const e=ge.getContext("webgl",{antialias:!0})||ge.getContext("experimental-webgl",{antialias:!0});we.WEBGL=!!e,we.WEBGL&&(we.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?we.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?we.FS_MAX_FLOAT_PRECISION="mediump":we.FS_MAX_FLOAT_PRECISION="lowp":we.FS_MAX_FLOAT_PRECISION="mediump",we.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),we.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),we.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),we.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),we.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),we.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),we.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),we.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),we.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),we.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){we.SUPPORTED_EXTENSIONS[e]=!0})))}const Te=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Ee extends C{constructor(e,t={}){super(e,t),this._backgroundColor=h.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.optimizeResizeDetection=!0,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=null,n=null,r=null,a=null,o=null,l=null,c=null,u=null,p=0;this._tick=this.scene.on("tick",(()=>{if(p++,s._canvasSizeChanged=!1,s.optimizeResizeDetection&&p<10)return;p=0;const e=this.canvas,t=this._resolutionScale!==i,h=window.innerWidth!==n||window.innerHeight!==r,A=e.clientWidth!==a||e.clientHeight!==o,f=e.offsetLeft!==l||e.offsetTop!==c,I=e.parentElement;if(t||h||A||f||I!==u){if(s._canvasSizeChanged=!0,this._spinner._adjustPosition(),t||A||f){const s=e.clientWidth,i=e.clientHeight;if(t||A){let t,s=0;for(const e in D.scenes)D.scenes.hasOwnProperty(e)&&(t=D.scenes[e],s+=Math.round(t.canvas.canvas.clientWidth*this._resolutionScale*(t.canvas.canvas.clientHeight*this._resolutionScale)));d.memory.pixels=s,e.width=Math.round(e.clientWidth*this._resolutionScale),e.height=Math.round(e.clientHeight*this._resolutionScale)}const n=this.boundary;n[0]=e.offsetLeft,n[1]=e.offsetTop,n[2]=s,n[3]=i,t||this.fire("boundary",n),a=s,o=i}t&&(i=this._resolutionScale),h&&(n=window.innerWidth,r=window.innerHeight),f&&(l=e.offsetLeft,c=e.offsetTop),u=I}})),this._spinner=new ve(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+h.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<Te.length;e++)try{this.gl=this.canvas.getContext(Te[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));{const e=this.gl;let t="__",s=e.activeTexture;e.activeTexture=function(e){t!==e&&(t=e,s.call(this,e))};let i={},n=e.bindTexture;e.bindTexture=function(e,s){i[t]!==s&&(i[t]=s,n.call(this,e,s))}}this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}getSnapshot(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}readPixels(e,t,s,i){return this.scene._renderer.readPixels(e,t,s,i)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,super.destroy()}}class be{constructor(e){this._scene=e,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1}getRTCViewMatrix(e,t){let s=this._rtcViewMats[e];return s||(s=this._getNewMat(),j(this._scene.camera.viewMatrix,t,s),this._rtcViewMats[e]=s),s}getRTCPickViewMatrix(e,t){let s=this._rtcPickViewMats[e];if(!s){s=this._getNewMat();const i=this.pickViewMatrix||this._scene.camera.viewMatrix;j(i,t,s),this._rtcPickViewMats[e]=s}return s}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=h.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}class _e{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get worldPos(){return this.entity&&this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1}}class De{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e<t.length;e++)i.push(e+1+": "+t[e]+"\n");this.errors=[],this.errors.push(""),this.errors.push(e.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(i.join(""))}}else this.errors=["Failed to allocate"]}destroy(){}}class Pe{constructor(e,t){this.bindTexture=function(s,i){return!!s.bind(i)&&(e.uniform1i(t,i),!0)}}}class Ce{constructor(e,t){this._gl=e,this.location=t}bindArrayBuffer(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}const Re=new e({});function Be(e){const t=[];let s,i;for(let n=0,r=e.length;n<r;n++)s=e[n],i=s.indexOf("/"),i>0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function xe(e){console.error(e.join("\n"))}class Se{constructor(e,t){this.id=Re.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new De(e,e.VERTEX_SHADER,Be(this.source.vertex)),this._fragmentShader=new De(e,e.FRAGMENT_SHADER,Be(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void xe(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void xe(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void xe(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void xe(this.errors);let t,s,i,n,r;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 xe(this.errors);const a=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;s<a;++s)i=e.getActiveUniform(this.handle,s),i&&(n=i.name,"\0"===n[n.length-1]&&(n=n.substr(0,n.length-1)),r=e.getUniformLocation(this.handle,n),i.type===e.SAMPLER_2D||i.type===e.SAMPLER_CUBE||35682===i.type||e instanceof WebGL2RenderingContext&&(i.type===e.UNSIGNED_INT_SAMPLER_2D||i.type===e.INT_SAMPLER_2D)?this.samplers[n]=new Pe(e,r):this.uniforms[n]=r);const o=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(s=0;s<o;s++)t=e.getActiveAttrib(this.handle,s),t&&(r=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new Ce(e,r));this.allocated=!0}bind(){this.allocated&&this.gl.useProgram(this.handle)}getLocation(e){if(this.allocated)return this.uniforms[e]}getAttribute(e){if(this.allocated)return this.attributes[e]}bindTexture(e,t,s){if(!this.allocated)return!1;const i=this.samplers[e];return!!i&&i.bindTexture(t,s)}destroy(){this.allocated&&(Re.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}class Oe{constructor(e,t,s,i,n,r,a,o,l){switch(this._gl=e,this.type=t,this.allocated=!1,s.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=r,this.length=0,this.dataLength=i,this.numItems=0,this.itemSize=n,this.normalized=!!a,this.stride=o||0,this.offset=l||0,this._allocate(s)}_allocate(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ne{constructor(e,t){this.scene=e,this.aabb=h.AABB3(),this.origin=h.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t<this.numMarkers;t++)if(this.markerList[t]){const s=this.markerList[t].worldPos;this.positions[e++]=s[0],this.positions[e++]=s[1],this.positions[e++]=s[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}_buildAABB(){const e=this.aabb;h.collapseAABB3(e),h.expandAABB3Points3(e,this.positions);const t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}_buildVBOs(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(this.positions);this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,s=this.numMarkers;this.positionsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new Oe(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),s,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,s=e.boundary,i=s[2],n=s[3];let r=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const s=this.markerList[e];if(s.viewPos[2]>-t){s._setVisible(!1);continue}const a=s.canvasPos,o=a[0],l=a[1];o+10<0||l+10<0||o-10>i||l-10>n?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[r++]=o,this.pixels[r++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s];if(t.active){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const i=0===e;this.sectionPlanesActive[s]=i}else this.sectionPlanesActive[s]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const Le=h.vec3([1,0,0]),Me=h.vec3();class Fe{constructor(e,t){this._scene=e,this._renderBufferManager=t,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=e.camera.on("viewMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s||(s=new Ne(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new Ne(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}_buildOcclusionLayersList(){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}_buildShaderSource(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}_buildVertexShaderSource(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = 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,s=e._sectionPlanesState;if(this._program=new Se(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._aPosition=i.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,s=this._program,i=e._sectionPlanesState,n=e.camera,r=e.camera.project;if(s.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,n._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,s=this._occlusionLayersList.length;e<s;e++){const s=this._occlusionLayersList[e];if(s.update(),s.culledBySectionPlanes)continue;const r=s.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,j(n.viewMatrix,r));const a=i.sectionPlanes.length;if(a>0){const e=i.sectionPlanes;for(let i=0;i<a;i++){const n=this._uSectionPlanes[i];if(n){const a=s.sectionPlanesActive[i];if(t.uniform1i(n.active,a?1:0),a){const s=e[i];t.uniform3fv(n.pos,W(s.dist,s.dir,r,Me)),t.uniform3fv(n.dir,s.dir)}}}}this._aPosition.bindArrayBuffer(s.positionsBuf);const o=s.indicesBuf;o.bind(),t.drawElements(t.POINTS,o.numItems,o.itemType,0)}}doOcclusionTest(){{const e=this._scene.canvas.resolutionScale,t=255*Le[0],s=255*Le[1],i=255*Le[2];for(let n=0,r=this._occlusionLayersList.length;n<r;n++){const r=this._occlusionLayersList[n];for(let n=0;n<r.lenOcclusionTestList;n++){const a=r.occlusionTestList[n],o=2*n,l=this._readPixelBuf.read(Math.round(r.pixels[o]*e),Math.round(r.pixels[o+1]*e)),c=l[0]===t&&l[1]===s&&l[2]===i;a._setVisible(c)}}}}unbindRenderBuf(){this._readPixelBuf.unbind()}destroy(){if(!this.destroyed){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}const He=h.vec2();class Ue{constructor(e){this._scene=e,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null}render(e){if(this._build(),this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=h.mat4();return()=>(e&&h.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,n=i.sao,r=t.drawingBufferWidth,a=t.drawingBufferHeight,o=i.camera.project._state,l=o.near,c=o.far,u=o.matrix,p=this._getInverseProjectMat(),d=Math.random(),A="perspective"===i.camera.projection;He[0]=r,He[1]=a,t.viewport(0,0,r,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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,c),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,u),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,p),t.uniform1i(this._uPerspective,A),t.uniform1f(this._uScale,n.scale*(c/5)),t.uniform1f(this._uIntensity,n.intensity),t.uniform1f(this._uBias,n.bias),t.uniform1f(this._uKernelRadius,n.kernelRadius),t.uniform1f(this._uMinResolution,n.minResolution),t.uniform2fv(this._uViewport,He),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();s.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Se(s,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const i=new Float32Array([1,1,0,1,0,0,1,0]),n=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),r=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Oe(s,s.ARRAY_BUFFER,n,n.length,3,s.STATIC_DRAW),this._uvBuf=new Oe(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new Oe(s,s.ELEMENT_ARRAY_BUFFER,r,r.length,1,s.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const Ge=new Float32Array(ze(17,[0,1])),Ve=new Float32Array(ze(17,[1,0])),je=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(We(i,t));return s}(17,4)),ke=new Float32Array(2);class Qe{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Se(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Oe(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new Oe(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Oe(e,e.ELEMENT_ARRAY_BUFFER,i,i.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=h.mat4();return()=>(e&&h.inverseMat4(r.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,n=this._program,r=this._scene,a=i.drawingBufferWidth,o=i.drawingBufferHeight,l=r.camera.project._state,c=l.near,u=l.far;i.viewport(0,0,a,o),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),n.bind(),ke[0]=a,ke[1]=o,i.uniform2fv(this._uViewport,ke),i.uniform1f(this._uCameraNear,c),i.uniform1f(this._uCameraFar,u),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,Ve):i.uniform2fv(this._uSampleOffsets,Ge),i.uniform1fv(this._uSampleWeights,je);const p=e.getDepthTexture(),d=t.getTexture();n.bindTexture(this._uDepthTexture,p,0),n.bindTexture(this._uOcclusionTexture,d,1),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()}}function We(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function ze(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class Ke{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(e=null){if(this._touch(e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}_touch(e=null){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const n=i.createTexture();let r;i.bindTexture(i.TEXTURE_2D,n),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),e?i.texStorage2D(i.TEXTURE_2D,1,e,t,s):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,s,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(r=i.createTexture(),i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const a=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,a),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const o=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,o),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,n,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,r,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,a),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,o),!i.isFramebuffer(o))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:o,renderbuf:a,texture:n,depthTexture:r,width:t,height:s},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,s=null,i=null,n=Uint8Array,r=4){const a=e,o=(this.buffer.height||this.gl.drawingBufferHeight)-t,l=new n(r),c=this.gl;return c.readPixels(a,o,1,1,s||c.RGBA,i||c.UNSIGNED_BYTE,l,0),l}readArray(e=null,t=null,s=Uint8Array,i=4){const n=new s(this.buffer.width*this.buffer.height*i),r=this.gl;return r.readPixels(0,0,this.buffer.width,this.buffer.height,e||r.RGBA,t||r.UNSIGNED_BYTE,n,0),n}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),s=t.pixelData,i=t.canvas,n=t.imageData,r=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const a=this.buffer.width,o=this.buffer.height,l=o/2|0,c=4*a,u=new Uint8Array(4*a);for(let e=0;e<l;++e){const t=e*c,i=(o-e-1)*c;u.set(s.subarray(t,t+c)),s.copyWithin(t,i,i+c),s.set(u,i)}return n.data.set(s),r.putImageData(n,0,0),i}readImage(e){const t=this.gl,s=this._getImageDataCache(),i=s.pixelData,n=s.canvas,r=s.imageData,a=s.context;t.readPixels(0,0,this.buffer.width,this.buffer.height,t.RGBA,t.UNSIGNED_BYTE,i),r.data.set(i),a.putImageData(r,0,0);let o=e.format||"png";return"jpeg"!==o&&"png"!==o&&"bmp"!==o&&(console.error("Unsupported image format: '"+o+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),o="png"),n.toDataURL(`image/${o}`)}_getImageDataCache(e=Uint8Array,t=4){const s=this.buffer.width,i=this.buffer.height;let n=this._imageDataCache;if(n&&(n.width===s&&n.height===i||(this._imageDataCache=null,n=null)),!n){const r=document.createElement("canvas"),a=r.getContext("2d");r.width=s,r.height=i,n={pixelData:new e(s*i*t),canvas:r,context:a,imageData:a.createImageData(s,i),width:s,height:i},this._imageDataCache=n}return n.context.resetTransform(),n}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}getTexture(){const e=this;return this._texture||(this._texture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.texture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.texture),!0)},unbind:function(t){e.buffer&&e.buffer.texture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}hasDepthTexture(){return this._hasDepthTexture}getDepthTexture(){if(!this._hasDepthTexture)return null;const e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}destroy(){if(this.allocated){const e=this.gl;e.deleteTexture(this.buffer.texture),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class Ye{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const s=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let i=s[e];return i||(i=new Ke(this.scene.canvas.canvas,this.scene.canvas.gl,t),s[e]=i),i}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Xe(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let s;switch(t){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(t)}return e._cachedExtensions[t]=s,s}var qe=function(){const e=[],t=[],s=[],i=[],n=[];let r=0;const a=new Uint16Array(3),o=new Uint16Array(3),l=new Uint16Array(3),c=h.vec3(),u=h.vec3(),p=h.vec3(),d=h.vec3(),A=h.vec3(),f=h.vec3(),I=h.vec3();return function(m,y,v,w){!function(n,r){const a={};let o,l,c,u;const h=Math.pow(10,4);let p,d,A=0;for(p=0,d=n.length;p<d;p+=3)o=n[p],l=n[p+1],c=n[p+2],u=Math.round(o*h)+"_"+Math.round(l*h)+"_"+Math.round(c*h),void 0===a[u]&&(a[u]=A/3,e[A++]=o,e[A++]=l,e[A++]=c),t[p/3]=a[u];for(p=0,d=r.length;p<d;p++)i[p]=t[r[p]],s[i[p]]=r[p]}(m,y),function(t,s){r=0;for(let m=0,y=t;m<y;m+=3){const t=3*i[m],y=3*i[m+1],v=3*i[m+2];s?(a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],o[0]=e[y],o[1]=e[y+1],o[2]=e[y+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],h.decompressPosition(a,s,c),h.decompressPosition(o,s,u),h.decompressPosition(l,s,p)):(c[0]=e[t],c[1]=e[t+1],c[2]=e[t+2],u[0]=e[y],u[1]=e[y+1],u[2]=e[y+2],p[0]=e[v],p[1]=e[v+1],p[2]=e[v+2]),h.subVec3(p,u,d),h.subVec3(c,u,A),h.cross3Vec3(d,A,f),h.normalizeVec3(f,I);const w=n[r]||(n[r]={normal:h.vec3()});w.normal[0]=I[0],w.normal[1]=I[1],w.normal[2]=I[2],r++}}(y.length,v);const g=[],T=Math.cos(h.DEGTORAD*w),E={};let b,_,D,P,C,R,B,x,S,O,N,L=!1;for(let e=0,t=y.length;e<t;e+=3){const t=e/3;for(let s=0;s<3;s++)b=i[e+s],_=i[e+(s+1)%3],D=Math.min(b,_),P=Math.max(b,_),C=D+","+P,void 0===E[C]?E[C]={index1:D,index2:P,face1:t,face2:void 0}:E[C].face2=t}for(C in E)R=E[C],void 0!==R.face2&&(B=n[R.face1].normal,x=n[R.face2].normal,S=h.dotVec3(B,x),S>T)||(O=s[R.index1],N=s[R.index2],(!L&&O>65535||N>65535)&&(L=!0),g.push(O),g.push(N));return L?new Uint32Array(g):new Uint16Array(g)}}();class Je{constructor(e,t,s,i,n=null,r=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.pickId=this.model.scene._renderer.getPickID(this),this.aabb=h.AABB3(),this._layer=n,this._portionId=r,this._color=[s[0],s[1],s[2],i],this._colorize=[s[0],s[1],s[2],i],this._colorizing=!1,this._transparent=i<255,this.numTriangles=0,this.origin=null}_finalize(e){this._layer.initFlags(this._portionId,e,this._transparent)}_finalize2(){this._layer.flushInitFlags&&this._layer.flushInitFlags()}_setVisible(e){this._layer.setVisible(this._portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this._layer.setColor(this._portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this._layer.setColor(this._portionId,this._colorize,false),this._colorizing=!0):(this._layer.setColor(this._portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const s=e<255,i=this._transparent!==s;this._color[3]=e,this._colorize[3]=e,this._transparent=s,this._colorizing?this._layer.setColor(this._portionId,this._colorize):this._layer.setColor(this._portionId,this._color),i&&this._layer.setTransparent(this._portionId,t,s)}_setOffset(e){this._layer.setOffset(this._portionId,e)}_setHighlighted(e){this._layer.setHighlighted(this._portionId,e,this._transparent)}_setXRayed(e){this._layer.setXRayed(this._portionId,e,this._transparent)}_setSelected(e){this._layer.setSelected(this._portionId,e,this._transparent)}_setEdges(e){this._layer.setEdges(this._portionId,e,this._transparent)}_setClippable(e){this._layer.setClippable(this._portionId,e,this._transparent)}_setCollidable(e){this._layer.setCollidable(this._portionId,e)}_setPickable(e){this._layer.setPickable(this._portionId,e,this._transparent)}_setCulled(e){this._layer.setCulled(this._portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,s,i){return!!this._layer.precisionRayPickSurface&&this._layer.precisionRayPickSurface(this._portionId,e,t,s,i)}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 Ze=0,$e=1,et=2,tt=3,st=4,it=5,nt=6,rt=7,at=8,ot=9,lt=10,ct=11,ut=new e({});class ht{constructor(e){this.id=ut.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ut.removeItem(this.id)}}const pt=function(){const e=h.mat4(),t=h.mat4();return function(s,i){i=i||h.mat4();const n=s[0],r=s[1],a=s[2],o=s[3]-n,l=s[4]-r,c=s[5]-a,u=65535;return h.identityMat4(e),h.translationMat4v(s,e),h.identityMat4(t),h.scalingMat4v([o/u,l/u,c/u],t),h.mulMat4(e,t,i),i}}();var dt=function(){const e=h.mat4(),t=h.mat4();return function(s,i,n){const r=new Uint16Array(s.length),a=new Float32Array([n[0]!==i[0]?65535/(n[0]-i[0]):0,n[1]!==i[1]?65535/(n[1]-i[1]):0,n[2]!==i[2]?65535/(n[2]-i[2]):0]);let o;for(o=0;o<s.length;o+=3)r[o+0]=Math.max(0,Math.min(65535,Math.floor((s[o+0]-i[0])*a[0]))),r[o+1]=Math.max(0,Math.min(65535,Math.floor((s[o+1]-i[1])*a[1]))),r[o+2]=Math.max(0,Math.min(65535,Math.floor((s[o+2]-i[2])*a[2])));h.identityMat4(e),h.translationMat4v(i,e),h.identityMat4(t),h.scalingMat4v([(n[0]-i[0])/65535,(n[1]-i[1])/65535,(n[2]-i[2])/65535],t);return{quantized:r,decodeMatrix:h.mulMat4(e,t,h.identityMat4())}}}();var At=function(){const e=h.mat3(),t=h.mat3();return function(s,i,n){const r=new Uint16Array(s.length),a=new Float32Array([65535/(n[0]-i[0]),65535/(n[1]-i[1])]);let o;for(o=0;o<s.length;o+=2)r[o+0]=Math.max(0,Math.min(65535,Math.floor((s[o+0]-i[0])*a[0]))),r[o+1]=Math.max(0,Math.min(65535,Math.floor((s[o+1]-i[1])*a[1])));h.identityMat3(e),h.translationMat3v(i,e),h.identityMat3(t),h.scalingMat3v([(n[0]-i[0])/65535,(n[1]-i[1])/65535],t);return{quantized:r,decodeMatrix:h.mulMat3(e,t,h.identityMat3())}}}();function ft(e,t,s,i){let n=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),r=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(r))*(n>=0?1:-1),t=(1-Math.abs(n))*(r>=0?1:-1);n=e,r=t}return new Int8Array([Math[s](127.5*n+(n<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function It(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const n=Math.sqrt(t*t+s*s+i*i);return[t/n,s/n,i/n]}function mt(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const yt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,n;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;i<e.length;i+=3)for(n=0;n<3;n++)t[n]=Math.min(t[n],e[i+n]),s[n]=Math.max(s[n],e[i+n]);return{min:t,max:s}},createPositionsDecodeMatrix:pt,compressPositions:dt,compressPosition:function(e,t,s){const i=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);s[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*i[0]))),s[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*i[1]))),s[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*i[2])))},decompressPositions:function(e,t,s=new Float32Array(e.length)){for(let i=0,n=e.length;i<n;i+=3)s[i+0]=e[i+0]*t[0]+t[12],s[i+1]=e[i+1]*t[5]+t[13],s[i+2]=e[i+2]*t[10]+t[14];return s},decompressPosition:function(e,t,s){return s[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14],s},decompressAABB:function(e,t,s=e){return s[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14],s[3]=e[3]*t[0]+t[12],s[4]=e[4]*t[5]+t[13],s[5]=e[5]*t[10]+t[14],s},getUVBounds:function(e){const t=new Float32Array(2),s=new Float32Array(2);let i,n;for(i=0;i<2;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;i<e.length;i+=2)for(n=0;n<2;n++)t[n]=Math.min(t[n],e[i+n]),s[n]=Math.max(s[n],e[i+n]);return{min:t,max:s}},compressUVs:At,decompressUVs:function(e,t,s=new Float32Array(e.length)){for(let i=0,n=e.length;i<n;i+=3)s[i+0]=e[i+0]*t[0]+t[6],s[i+1]=e[i+1]*t[4]+t[7];return s},decompressUV:function(e,t,s){s[0]=e[0]*t[0]+t[6],s[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let s,i,n,r,a;for(let o=0;o<e.length;o+=3)n=s=ft(e,o,"floor","floor"),i=It(s),r=a=mt(e,o,i),s=ft(e,o,"ceil","floor"),i=It(s),r=mt(e,o,i),r>a&&(n=s,a=r),s=ft(e,o,"floor","ceil"),i=It(s),r=mt(e,o,i),r>a&&(n=s,a=r),s=ft(e,o,"ceil","ceil"),i=It(s),r=mt(e,o,i),r>a&&(n=s,a=r),t[o]=n[0],t[o+1]=n[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,n=e.length;s<n;s+=2){let n=e[s+0],r=e[s+1];n=(2*n+1)/255,r=(2*r+1)/255;const a=1-Math.abs(n)-Math.abs(r);a<0&&(n=(1-Math.abs(r))*(n>=0?1:-1),r=(1-Math.abs(n))*(r>=0?1:-1));const o=Math.sqrt(n*n+r*r+a*a);t[i+0]=n/o,t[i+1]=r/o,t[i+2]=a/o,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const n=1-Math.abs(s)-Math.abs(i);n<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const r=Math.sqrt(s*s+i*i+n*n);return t[0]=s/r,t[1]=i/r,t[2]=n/r,t}};class vt extends C{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ht({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.viewport.boundary,t=e[2]/e[3],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),h.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,n){const r=this.scene.canvas.canvas,a=r.offsetWidth/2,o=r.offsetHeight/2;return s[0]=(e[0]-a)/a,s[1]=(e[1]-o)/o,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,i,n),n}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class wt extends C{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ht({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,s=e.viewport.boundary,i=s[2],n=s[3],r=i/n;let a,o,l,c;i>n?(a=-t,o=t,l=t/r,c=-t/r):(a=-t*r,o=t*r,l=t,c=-t),h.orthoMat4c(a,o,c,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,n){const r=this.scene.canvas.canvas,a=r.offsetWidth/2,o=r.offsetHeight/2;return s[0]=(e[0]-a)/a,s[1]=(e[1]-o)/o,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,i,n),n}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class gt extends C{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ht({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){h.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,n){const r=this.scene.canvas.canvas,a=r.offsetWidth/2,o=r.offsetHeight/2;return s[0]=(e[0]-a)/a,s[1]=(e[1]-o)/o,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,i,n),n}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Tt extends C{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ht({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,n){const r=this.scene.canvas.canvas,a=r.offsetWidth/2,o=r.offsetHeight/2;return s[0]=(e[0]-a)/a,s[1]=(e[1]-o)/o,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,i,n),n}destroy(){super.destroy(),this._state.destroy()}}const Et=h.vec3(),bt=h.vec3(),_t=h.vec3(),Dt=h.vec3(),Pt=h.vec3(),Ct=h.vec3(),Rt=h.vec4(),Bt=h.vec4(),xt=h.vec4(),St=h.mat4(),Ot=h.mat4(),Nt=h.vec3(),Lt=h.vec3(),Mt=h.vec3(),Ft=h.vec3();class Ht extends C{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new ht({deviceMatrix:h.mat4(),hasDeviceMatrix:!1,matrix:h.mat4(),normalMatrix:h.mat4(),inverseMatrix:h.mat4()}),this._perspective=new vt(this),this._ortho=new wt(this),this._frustum=new gt(this),this._customProjection=new Tt(this),this._project=this._perspective,this._eye=h.vec3([0,0,10]),this._look=h.vec3([0,0,0]),this._up=h.vec3([0,1,0]),this._worldUp=h.vec3([0,1,0]),this._worldRight=h.vec3([1,0,0]),this._worldForward=h.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(h.subVec3(this._eye,this._look,Nt),h.normalizeVec3(Nt,Lt),h.mulVec3Scalar(Lt,1e3,Mt),h.addVec3(this._look,Mt,Ft),t=Ft):t=this._eye,e.hasDeviceMatrix?(h.lookAtMat4v(t,this._look,this._up,Ot),h.mulMat4(e.deviceMatrix,Ot,e.matrix)):h.lookAtMat4v(t,this._look,this._up,e.matrix),h.inverseMat4(this._state.matrix,this._state.inverseMatrix),h.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=h.subVec3(this._eye,this._look,Et);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,St),t=h.transformPoint3(St,t,bt),this.eye=h.addVec3(this._look,t,_t),this.up=h.transformPoint3(St,this._up,Dt)}orbitPitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._eye,this._look,Et);const s=h.cross3Vec3(h.normalizeVec3(t,bt),h.normalizeVec3(this._up,_t));h.rotationMat4v(.0174532925*e,s,St),t=h.transformPoint3(St,t,Dt),this.up=h.transformPoint3(St,this._up,Pt),this.eye=h.addVec3(t,this._look,Ct)}yaw(e){let t=h.subVec3(this._look,this._eye,Et);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,St),t=h.transformPoint3(St,t,bt),this.look=h.addVec3(t,this._eye,_t),this._gimbalLock&&(this.up=h.transformPoint3(St,this._up,Dt))}pitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._look,this._eye,Et);const s=h.cross3Vec3(h.normalizeVec3(t,bt),h.normalizeVec3(this._up,_t));h.rotationMat4v(.0174532925*e,s,St),this.up=h.transformPoint3(St,this._up,Ct),t=h.transformPoint3(St,t,Dt),this.look=h.addVec3(t,this._eye,Pt)}pan(e){const t=h.subVec3(this._eye,this._look,Et),s=[0,0,0];let i;if(0!==e[0]){const n=h.cross3Vec3(h.normalizeVec3(t,[]),h.normalizeVec3(this._up,bt));i=h.mulVec3Scalar(n,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=h.mulVec3Scalar(h.normalizeVec3(this._up,_t),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=h.mulVec3Scalar(h.normalizeVec3(t,Dt),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=h.addVec3(this._eye,s,Pt),this.look=h.addVec3(this._look,s,Ct)}zoom(e){const t=h.subVec3(this._eye,this._look,Et),s=Math.abs(h.lenVec3(t,bt)),i=Math.abs(s+e);if(i<.5)return;const n=h.normalizeVec3(t,_t);this.eye=h.addVec3(this._look,h.mulVec3Scalar(n,i),Dt)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=h.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return h.lenVec3(h.subVec3(this._look,this._eye,Et))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=Rt,s=Bt,i=xt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,h.mulMat4v4(this.viewMatrix,t,s),h.mulMat4v4(this.projMatrix,s,i),h.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const n=this.scene.canvas.canvas,r=n.offsetWidth/2,a=n.offsetHeight/2;return[i[0]*r+r,i[1]*a+a]}destroy(){super.destroy(),this._state.destroy()}}const Ut=h.vec4(),Gt=h.vec3();class Vt{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){const i=this._scene,n=i.camera,r=t.model,a=i.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=n.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s);const p=i._sectionPlanesState.sectionPlanes.length;if(p>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,n=r.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const r=n.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,r?1:0),r){const s=e[t];if(c){const e=W(s.dist,s.dir,c,Gt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uLightAmbient=i.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const n=s.lights;let r;for(let e=0,t=n.length;e<t;e++)switch(r=n[e],r.type){case"dir":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=i.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=i.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=i.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=i.getLocation("lightPos"+e),this._uLightDir[e]=i.getLocation("lightDir"+e),this._uLightAttenuation[e]=i.getLocation("lightAttenuation"+e)}this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=i.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,i=this._program,n=t._lightsState.lights,r=t.camera.project;i.bind(),this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=n.length;e<t;e++){const t=n[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const i=t.sao;if(i.possible){const t=s.drawingBufferWidth,n=s.drawingBufferHeight;Ut[0]=t,Ut[1]=n,Ut[2]=i.blendCutoff,Ut[3]=i.blendFactor,s.uniform4fv(this._uSAOParams,Ut),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>0;let n;const r=[];r.push("#version 300 es"),r.push("// Triangles dataTexture draw vertex shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("precision highp usampler2D;"),r.push("precision highp isampler2D;"),r.push("precision highp sampler2D;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("precision mediump usampler2D;"),r.push("precision mediump isampler2D;"),r.push("precision mediump sampler2D;"),r.push("#endif"),r.push("uniform int renderPass;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),r.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),r.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),r.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),r.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),r.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),r.push("uniform highp sampler2D uTextureCameraMatrices;"),r.push("uniform highp sampler2D uTextureModelMatrices;"),r.push("uniform vec3 uCameraEyeRtc;"),r.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("out float isPerspective;")),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++)n=s.lights[e],"ambient"!==n.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===n.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===n.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===n.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")));i&&(r.push("out vec4 vWorldPosition;"),r.push("flat out uint vFlags2;")),r.push("out vec4 vColor;"),r.push("void main(void) {"),r.push("int polygonIndex = gl_VertexID / 3;"),r.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),r.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),r.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),r.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),r.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),r.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),r.push("if (int(flags.x) != renderPass) {"),r.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),r.push(" return;"),r.push("} else {"),r.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),r.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),r.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),r.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),r.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),r.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),r.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),r.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),r.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),r.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),r.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),r.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),r.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),r.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),r.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),r.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),r.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),r.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),r.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),r.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),r.push("if (color.a == 0u) {"),r.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),r.push(" return;"),r.push("};"),r.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),r.push("vec3 position;"),r.push("position = positions[gl_VertexID % 3];"),r.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),r.push("if (solid != 1u) {"),r.push("if (isPerspectiveMatrix(projMatrix)) {"),r.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),r.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),r.push("position = positions[2 - (gl_VertexID % 3)];"),r.push("viewNormal = -viewNormal;"),r.push("}"),r.push("} else {"),r.push("if (viewNormal.z < 0.0) {"),r.push("position = positions[2 - (gl_VertexID % 3)];"),r.push("viewNormal = -viewNormal;"),r.push("}"),r.push("}"),r.push("}"),r.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),r.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),r.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;");for(let e=0,t=s.lights.length;e<t;e++)if(n=s.lights[e],"ambient"!==n.type){if("dir"===n.type)"view"===n.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===n.type)"view"===n.space?r.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==n.type)continue;"view"===n.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return r.push("vec3 rgb = vec3(color.rgb) / 255.0;"),r.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags2 = flags2.r;")),r.push("gl_Position = clipPos;"),r.push("}"),r.push("}"),r}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const jt=new Float32Array([1,1,1]);h.vec4();const kt=h.vec3();class Qt{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,n=i.camera,r=t.model,a=i.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=n.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s),s===it){const e=i.xrayMaterial._state,t=e.fillColor,s=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===tt){const e=i.highlightMaterial._state,t=e.fillColor,s=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===st){const e=i.selectedMaterial._state,t=e.fillColor,s=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else a.uniform4fv(this._uColor,jt);const p=i._sectionPlanesState.sectionPlanes.length;if(p>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,n=r.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const r=n.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,r?1:0),r){const s=e[t];if(c){const e=W(s.dist,s.dir,c,kt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,i=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.y) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("varying float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("uniform vec4 color;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Wt=h.vec3(),zt=new Float32Array([0,0,0,1]);class Kt{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;if(!this._program&&(this._allocate(t),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),a.uniform1i(this._uRenderPass,s),s===lt){const e=n.xrayMaterial._state,t=e.edgeColor,s=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===at){const e=n.highlightMaterial._state,t=e.edgeColor,s=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===ot){const e=n.selectedMaterial._state,t=e.edgeColor,s=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],s)}else a.uniform4fv(this._uColor,zt);a.uniformMatrix4fv(this._uViewMatrix,!1,c?j(r.viewMatrix,c):r.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,i.worldMatrix);const u=n._sectionPlanesState.sectionPlanes.length;if(u>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*u,r=i.renderFlags;for(let t=0;t<u;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,Wt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),a.drawArrays(a.LINES,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),a.drawArrays(a.LINES,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),a.drawArrays(a.LINES,0,o.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets"}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=this._program,i=e.camera.project;if(s.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yt=h.vec3();class Xt{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene;n.camera;const r=n.canvas.gl,a=t._state,o=a.textureState,l=t._state.origin;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),e.pickViewMatrix&&o.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),r.uniform1i(this._uRenderPass,s);const c=n._sectionPlanesState.sectionPlanes.length;if(c>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*c,a=i.renderFlags;for(let t=0;t<c;t++){const i=this._uSectionPlanes[t];if(i){const n=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(i.active,n?1:0),n){const s=e[t];if(l){const e=W(s.dist,s.dir,l,Yt);r.uniform3fv(i.pos,e)}else r.uniform3fv(i.pos,s.pos);r.uniform3fv(i.dir,s.dir)}}}}a.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),r.drawArrays(r.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),r.drawArrays(r.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),r.drawArrays(r.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets"}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=this._program,i=e.camera.project;if(s.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vec4 rgb = vec4(color.rgba);"),s.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const qt=h.vec3();class Jt{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s),n.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const p=n._sectionPlanesState.sectionPlanes.length;if(p>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,r=i.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,qt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("smooth out vec4 vWorldPosition;"),s.push("flat out uvec4 vFlags2;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("uniform bool sectionPlaneActive"+n+";"),i.push("uniform vec3 sectionPlanePos"+n+";"),i.push("uniform vec3 sectionPlaneDir"+n+";")}if(i.push("in vec4 vPickColor;"),i.push("out vec4 outPickColor;"),i.push("void main(void) {"),s){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Zt=h.vec3();class $t{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniform1f(this._uPickZNear,e.pickZNear),a.uniform1f(this._uPickZFar,e.pickZFar),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const p=n._sectionPlanesState.sectionPlanes.length;if(p>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,r=i.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,Zt);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPackedVertexId=s.getAttribute("packedVertexId"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("uniform bool sectionPlaneActive"+n+";"),i.push("uniform vec3 sectionPlanePos"+n+";"),i.push("uniform vec3 sectionPlaneDir"+n+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 packDepth(const in float depth) {"),i.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),i.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),i.push(" vec4 res = fract(depth * bitShift);"),i.push(" res -= res.xxyz * bitMask;"),i.push(" return res;"),i.push("}"),i.push("out vec4 outPackedDepth;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const es=h.vec3();function ts(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t}class ss{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;e._origin[0]=c[0],e._origin[1]=c[1],e._origin[2]=c[2];const u=t.aabb,h=2e9,p=[ts(u[3]-u[0])*h,ts(u[4]-u[1])*h,ts(u[5]-u[2])*h];e._coordinateScale[0]=ts(p[0]),e._coordinateScale[1]=ts(p[1]),e._coordinateScale[2]=ts(p[2]),this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let d=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),d=e.pickOrigin||d);const A=[d[0]-c[0],d[1]-c[1],d[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this._u_vectorA,e._vectorA),a.uniform2fv(this._u_invVectorAB,e._invVectorAB),a.uniform1i(this._u_layerNumber,e._layerNumber),a.uniform3fv(this._u_coordinateScaler,p),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniform1f(this._uPickZNear,e.pickZNear),a.uniform1f(this._uPickZFar,e.pickZFar),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const f=n._sectionPlanesState.sectionPlanes.length;if(f>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*f,r=i.renderFlags;for(let t=0;t<f;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,es);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}const I="edge"===e._snapMode?a.LINES:a.POINTS;o.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),a.drawArrays(I,0,o.numEdgeIndices8Bits)),o.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),a.drawArrays(I,0,o.numEdgeIndices16Bits)),o.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),a.drawArrays(I,0,o.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPackedVertexId=s.getAttribute("packedVertexId"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this._u_vectorA=s.getLocation("_vectorA"),this._u_invVectorAB=s.getLocation("_invVectorAB"),this._u_layerNumber=s.getLocation("_layerNumber"),this._u_coordinateScaler=s.getLocation("_coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 _vectorA;"),s.push("uniform vec2 _invVectorAB;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - _vectorA.x) * _invVectorAB.x;"),s.push(" float y = (clipPos.y - _vectorA.y) * _invVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vViewPosition = clipPos;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),i.push("uniform int _layerNumber;"),i.push("uniform vec3 _coordinateScaler;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*_coordinateScaler.xyz, _layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}h.vec4();const is=h.vec3();function ns(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t}class rs{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;e._origin[0]=c[0],e._origin[1]=c[1],e._origin[2]=c[2];const u=t.aabb,h=2e9,p=[ns(u[3]-u[0])*h,ns(u[4]-u[1])*h,ns(u[5]-u[2])*h];e._coordinateScale[0]=ns(p[0]),e._coordinateScale[1]=ns(p[1]),e._coordinateScale[2]=ns(p[2]),this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let d=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),d=e.pickOrigin||d);const A=[d[0]-c[0],d[1]-c[1],d[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this._u_vectorA,e._vectorA),a.uniform2fv(this._u_invVectorAB,e._invVectorAB),a.uniform1i(this._u_layerNumber,e._layerNumber),a.uniform3fv(this._u_coordinateScaler,p),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniform1f(this._uPickZNear,e.pickZNear),a.uniform1f(this._uPickZFar,e.pickZFar),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const f=n._sectionPlanesState.sectionPlanes.length;if(f>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*f,r=i.renderFlags;for(let t=0;t<f;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,is);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPackedVertexId=s.getAttribute("packedVertexId"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this._u_vectorA=s.getLocation("_vectorA"),this._u_invVectorAB=s.getLocation("_invVectorAB"),this._u_layerNumber=s.getLocation("_layerNumber"),this._u_coordinateScaler=s.getLocation("_coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture draw vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 _vectorA;"),s.push("uniform vec2 _invVectorAB;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - _vectorA.x) * _invVectorAB.x;"),s.push(" float y = (clipPos.y - _vectorA.y) * _invVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.001;"),s.push("clipPos.xyzw *= tmp;"),s.push("vViewPosition = clipPos;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),i.push("uniform int _layerNumber;"),i.push("uniform vec3 _coordinateScaler;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*_coordinateScaler.xyz, - _layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const as=h.vec3();class os{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=r.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];if(a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s),a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uPickInvisible,e.pickInvisible),n.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const p=n._sectionPlanesState.sectionPlanes.length;if(p>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,r=i.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(c){const e=W(s.dist,s.dir,c,as);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick normals vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureCameraMatrices;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),s.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),s.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("normal = -normal;"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("normal = -normal;"),s.push("}"),s.push("}"),s.push("}"),s.push("normal = -normal;"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vWorldNormal = normal.xyz;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.w;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("uniform bool sectionPlaneActive"+n+";"),i.push("uniform vec3 sectionPlanePos"+n+";"),i.push("uniform vec3 sectionPlaneDir"+n+";")}if(i.push("in vec3 vWorldNormal;"),i.push("out vec4 outNormal;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outNormal = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}h.vec3();class ls{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("// Triangles dataTexture occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("varying float isPerspective;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(we.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;")),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("// Triangles dataTexture occlusion fragment shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("varying float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("varying float vFragDepth;")),s){i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("void main(void) {"),s){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)i.push(" if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}h.vec4();const cs=h.vec3();class us{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,n=i.camera,r=t.model,a=i.canvas.gl,o=t._state,l=o.textureState,c=t._state.origin;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,o)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureCameraMatrices,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);let u=n.eye;e.pickViewMatrix&&(l.bindPickCameraTexture(this._program,this._uTextureCameraMatrices),u=e.pickOrigin||u);const h=[u[0]-c[0],u[1]-c[1],u[2]-c[2]];a.uniform3fv(this._uCameraEyeRtc,h),a.uniform1i(this._uRenderPass,s);const p=i._sectionPlanesState.sectionPlanes.length;if(p>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*p,n=r.renderFlags;for(let t=0;t<p;t++){const i=this._uSectionPlanes[t];if(i){const r=n.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,r?1:0),r){const s=e[t];if(c){const e=W(s.dist,s.dir,c,cs);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}o.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTextureCameraMatrices="uTextureCameraMatrices",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectIdOffsets="uTexturePerObjectIdOffsets",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,i=this._program,n=t.camera.project;if(i.bind(),s.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState;e._lightsState;const s=t.sectionPlanes.length>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureCameraMatrices;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),s&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("mat4 viewMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 0), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 0), 0));"),i.push("mat4 viewNormalMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 1), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 1), 0));"),i.push("mat4 projMatrix = mat4 (texelFetch (uTextureCameraMatrices, ivec2(0, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(1, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(2, 2), 0), texelFetch (uTextureCameraMatrices, ivec2(3, 2), 0));"),i.push("mat4 worldMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 0), 0), texelFetch (uTextureModelMatrices, ivec2(1, 0), 0), texelFetch (uTextureModelMatrices, ivec2(2, 0), 0), texelFetch (uTextureModelMatrices, ivec2(3, 0), 0));"),i.push("mat4 worldNormalMatrix = mat4 (texelFetch (uTextureModelMatrices, ivec2(0, 1), 0), texelFetch (uTextureModelMatrices, ivec2(1, 1), 0), texelFetch (uTextureModelMatrices, ivec2(2, 1), 0), texelFetch (uTextureModelMatrices, ivec2(3, 1), 0));"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const hs=h.vec3();class ps{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=t._state.origin;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t)),a.uniform1i(this._uRenderPass,s),a.uniformMatrix4fv(this._uViewMatrix,!1,l?j(r.viewMatrix,l):r.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,i.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,i.worldNormalMatrix);const c=n._sectionPlanesState.sectionPlanes.length;if(c>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*c,r=i.renderFlags;for(let t=0;t<c;t++){const i=this._uSectionPlanes[t];if(i){const n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(l){const e=W(s.dist,s.dir,l,hs);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aOffset.bindArrayBuffer(o.offsetsBuf),this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor.bindArrayBuffer(o.colorsBuf),this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),o.indicesBuf.bind(),a.drawElements(a.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2&&(this._aFlags2=s.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec3 normal;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 worldNormalMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 viewNormalMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("varying float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec3 vViewNormal;"),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(we.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;")),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("varying float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("varying float vFragDepth;")),s){i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("varying vec3 vViewNormal;"),i.push("vec3 packNormalToRGB( const in vec3 normal ) {"),i.push(" return normalize( normal ) * 0.5 + 0.5;"),i.push("}"),i.push("void main(void) {"),s){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}h.vec3();class ds{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=i.getLocation("zFar")),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),t.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastLightId=null}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("// Batched geometry shadow vertex shader"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec4 vViewPosition;"),s.push("void main(void) {"),s.push(" bool visible = (float(flags.x) > 0.0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("varying vec4 vViewPosition;"),s.push("vec4 encodeFloat( const in float v ) {"),s.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),s.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),s.push(" vec4 comp = fract(v * bitShift);"),s.push(" comp -= comp.xxyz * bitMask;"),s.push(" return comp;"),s.push("}"),s.push("void main(void) {"),t){s.push(" bool clippable = (float(vFlags2.x) > 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i<e.sectionPlanes.length;i++)s.push(" if (sectionPlaneActive"+i+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const As=h.vec4(),fs=h.vec3(),Is={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"};class ms{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){const i=this._scene,n=i.camera,r=t.model,a=i.canvas.gl,o=t._state,l=t._state.origin;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,s),a.uniformMatrix4fv(this._uViewMatrix,!1,l?j(n.viewMatrix,l):n.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,r.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,r.worldNormalMatrix);const c=i._sectionPlanesState.sectionPlanes.length;if(c>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*c,n=r.renderFlags;for(let t=0;t<c;t++){const i=this._uSectionPlanes[t];if(i){const r=n.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,r?1:0),r){const s=e[t];if(l){const e=W(s.dist,s.dir,l,fs);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(o.colorsBuf),this._aMetallicRoughness&&this._aMetallicRoughness.bindArrayBuffer(o.metallicRoughnessBuf),this._aFlags&&this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(o.offsetsBuf),o.indicesBuf.bind(),a.drawElements(a.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uGammaFactor=i.getLocation("gammaFactor"),this._uLightAmbient=i.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const n=s.lights;let r;for(let e=0,t=n.length;e<t;e++)switch(r=n[e],r.type){case"dir":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=i.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=i.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=i.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=i.getLocation("lightColor"+e),this._uLightPos[e]=i.getLocation("lightPos"+e),this._uLightDir[e]=i.getLocation("lightDir"+e),this._uLightAttenuation[e]=i.getLocation("lightAttenuation"+e)}s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aMetallicRoughness=i.getAttribute("metallicRoughness"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=i.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(e){const t=we.MAX_TEXTURE_UNITS,s=this._scene,i=s.canvas.gl,n=this._program,r=s._lightsState,a=r.lights,o=s.camera.project;n.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,s._lightsState.getAmbientColorAndIntensity());for(let e=0,t=a.length;e<t;e++){const t=a[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}if(r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(n.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.lightMaps.length>0&&r.lightMaps[0].texture&&this._uLightMap&&(n.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._withSAO){const n=s.sao;if(n.possible){const s=i.drawingBufferWidth,r=i.drawingBufferHeight;As[0]=s,As[1]=r,As[2]=n.blendCutoff,As[3]=n.blendFactor,i.uniform4fv(this._uSAOParams,As),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++}}if(s.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&i.uniform1f(this._uGammaFactor,s.gammaFactor)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>0,n=t.clippingCaps,r=[];return r.push("// Triangles dataTexture quality draw vertex shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("uniform int renderPass;"),r.push("attribute vec3 position;"),r.push("attribute vec3 normal;"),r.push("attribute vec4 color;"),r.push("attribute vec2 metallicRoughness;"),r.push("attribute vec4 flags;"),r.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&r.push("attribute vec3 offset;"),r.push("uniform mat4 worldMatrix;"),r.push("uniform mat4 worldNormalMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform mat4 viewNormalMatrix;"),r.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("varying float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("varying float isPerspective;")),r.push("vec3 octDecode(vec2 oct) {"),r.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),r.push(" if (v.z < 0.0) {"),r.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);"),r.push(" }"),r.push(" return normalize(v);"),r.push("}"),r.push("varying vec4 vViewPosition;"),r.push("varying vec3 vViewNormal;"),r.push("varying vec4 vColor;"),r.push("varying vec2 vMetallicRoughness;"),s.lightMaps.length>0&&r.push("varying vec3 vWorldNormal;"),i&&(r.push("varying vec4 vWorldPosition;"),r.push("varying vec4 vFlags2;"),n&&r.push("varying vec4 vClipPosition;")),r.push("void main(void) {"),r.push("if (int(flags.x) != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),r.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),we.SUPPORTED_EXTENSIONS.EXT_frag_depth?r.push("vFragDepth = 1.0 + clipPos.w;"):(r.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),r.push("clipPos.z *= clipPos.w;"))),i&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags2 = flags2;"),n&&r.push("vClipPosition = clipPos;")),r.push("vViewPosition = viewPosition;"),r.push("vViewNormal = viewNormal;"),r.push("vColor = color;"),r.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&r.push("vWorldNormal = worldNormal.xyz;"),r.push("gl_Position = clipPos;"),r.push("}"),r.push("}"),r}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState,n=s.sectionPlanes.length>0,r=s.clippingCaps,a=[];a.push("// Triangles dataTexture quality draw fragment shader"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(a.push("varying float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("varying float vFragDepth;")),a.push("varying vec4 vViewPosition;"),a.push("varying vec3 vViewNormal;"),a.push("varying vec4 vColor;"),a.push("varying vec2 vMetallicRoughness;"),i.lightMaps.length>0&&a.push("varying vec3 vWorldNormal;"),a.push("uniform mat4 viewMatrix;"),i.reflectionMaps.length>0&&a.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&a.push("uniform samplerCube lightMap;"),a.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),r&&a.push("varying vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("#define PI 3.14159265359"),a.push("#define RECIPROCAL_PI 0.31830988618"),a.push("#define RECIPROCAL_PI2 0.15915494"),a.push("#define EPSILON 1e-6"),a.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),a.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),a.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),a.push("}"),a.push("struct IncidentLight {"),a.push(" vec3 color;"),a.push(" vec3 direction;"),a.push("};"),a.push("struct ReflectedLight {"),a.push(" vec3 diffuse;"),a.push(" vec3 specular;"),a.push("};"),a.push("struct Geometry {"),a.push(" vec3 position;"),a.push(" vec3 viewNormal;"),a.push(" vec3 worldNormal;"),a.push(" vec3 viewEyeDir;"),a.push("};"),a.push("struct Material {"),a.push(" vec3 diffuseColor;"),a.push(" float specularRoughness;"),a.push(" vec3 specularColor;"),a.push(" float shine;"),a.push("};"),a.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),a.push(" float r = ggxRoughness + 0.0001;"),a.push(" return (2.0 / (r * r) - 2.0);"),a.push("}"),a.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),a.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),a.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),a.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),a.push("}"),i.reflectionMaps.length>0&&(a.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),a.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),a.push(" vec3 envMapColor = "+Is[i.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),a.push(" return envMapColor;"),a.push("}")),a.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),a.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),a.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),a.push("}"),a.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),a.push(" float a2 = ( alpha * alpha );"),a.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),a.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),a.push(" return 1.0 / ( gl * gv );"),a.push("}"),a.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),a.push(" float a2 = ( alpha * alpha );"),a.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),a.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),a.push(" return 0.5 / max( gv + gl, EPSILON );"),a.push("}"),a.push("float D_GGX(const in float alpha, const in float dotNH) {"),a.push(" float a2 = ( alpha * alpha );"),a.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),a.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),a.push("}"),a.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),a.push(" float alpha = ( roughness * roughness );"),a.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),a.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),a.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),a.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),a.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),a.push(" vec3 F = F_Schlick( specularColor, dotLH );"),a.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),a.push(" float D = D_GGX( alpha, dotNH );"),a.push(" return F * (G * D);"),a.push("}"),a.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),a.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),a.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),a.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),a.push(" vec4 r = roughness * c0 + c1;"),a.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),a.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),a.push(" return specularColor * AB.x + AB.y;"),a.push("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(a.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(a.push(" vec3 irradiance = "+Is[i.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),a.push(" irradiance *= PI;"),a.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),a.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),i.reflectionMaps.length>0&&(a.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),a.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),a.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),a.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),a.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),a.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),a.push("}")),a.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),a.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),a.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),a.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),a.push("}"),a.push("void main(void) {"),n){a.push(" bool clippable = (float(vFlags2.x) > 0.0);"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");r?(a.push(" if (dist > (0.002 * vClipPosition.w)) {"),a.push(" discard;"),a.push(" }"),a.push(" if (dist > 0.0) { "),a.push(" gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push(" gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push(" return;"),a.push("}")):(a.push(" if (dist > 0.0) { "),a.push(" discard;"),a.push(" }")),a.push("}")}a.push("IncidentLight light;"),a.push("Material material;"),a.push("Geometry geometry;"),a.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),a.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),a.push("float alpha = float(vColor.a) / 255.0;"),a.push("vec3 diffuseColor = rgb;"),a.push("float specularF0 = 1.0;"),a.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),a.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),a.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),a.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),a.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),a.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);"),a.push("geometry.position = vViewPosition.xyz;"),a.push("geometry.viewNormal = -normalize(vViewNormal);"),a.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),i.lightMaps.length>0&&a.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&a.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("light.direction = normalize(lightDir"+e+");"):a.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):a.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?a.push("light.direction = normalize(lightDir"+e+");"):a.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),a.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return a.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular);"),a.push("vec4 fragColor;"),this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push(" fragColor = vec4(outgoingLight.rgb * ambient, alpha);")):a.push(" fragColor = vec4(outgoingLight.rgb, alpha);"),t&&a.push("fragColor = linearToGamma(fragColor, gammaFactor);"),a.push("gl_FragColor = fragColor;"),e.logarithmicDepthBufferEnabled&&we.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ys=h.vec3();class vs{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,n=i.scene,r=n.camera,a=n.canvas.gl,o=t._state,l=t._state.origin;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),this._program.bindTexture(this._uTexturePerObjectIdPositionsDecodeMatrix,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerObjectIdPositionsDecodeMatrix),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},1),this._program.bindTexture(this._uTexturePerVertexIdCoordinates,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerVertexIdCoordinates),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},2),this._program.bindTexture(this._uTexturePerObjectIdColorsAndFlags,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerObjectIdColorsAndFlags),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},3),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniformMatrix4fv(this._uWorldMatrix,!1,i.worldMatrix);const c=e.pickViewMatrix||r.viewMatrix,u=l?j(c,l):c;if(a.uniformMatrix4fv(this._uViewMatrix,!1,u),a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const h=n._sectionPlanesState.sectionPlanes.length;if(h>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*h,r=i.renderFlags;for(let t=0;t<h;t++){const i=this._uSectionPlanes[t],n=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(i.active,n?1:0),n){const s=e[t];if(l){const e=W(s.dist,s.dir,l,ys);a.uniform3fv(i.pos,e)}else a.uniform3fv(i.pos,s.pos);a.uniform3fv(i.dir,s.dir)}}}o.numIndices8Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdPortionIds8Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdIndices8Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},5),a.drawArrays(a.TRIANGLES,0,o.numIndices8Bits)),o.numIndices16Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdPortionIds16Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdIndices16Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},5),a.drawArrays(a.TRIANGLES,0,o.numIndices16Bits)),o.numIndices32Bits>0&&(this._program.bindTexture(this._uTexturePerPolygonIdPortionIds,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdPortionIds32Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},4),this._program.bindTexture(this._uTexturePerPolygonIdIndices,{bind:function(e){return a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,o.texturePerPolygonIdIndices32Bits),!0},unbind:function(e){a.activeTexture(a["TEXTURE"+e]),a.bindTexture(a.TEXTURE_2D,null)}},5),a.drawArrays(a.TRIANGLES,0,o.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPackedVertexId=s.getAttribute("packedVertexId"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uTexturePerObjectIdPositionsDecodeMatrix="uTexturePerObjectIdPositionsDecodeMatrix",this._uTexturePerObjectIdColorsAndFlags="uTexturePerObjectIdColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds"}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick flat normals vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in uvec3 packedVertexId;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform isampler2D uTexturePerPolygonIdNormals;"),s.push("uniform usampler2D uTexturePerPolygonIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out int vFlags2;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_normal_index = polygonIndex & 4095;"),s.push("int v_normal_index = polygonIndex >> 12;"),s.push("int h_packed_object_id_index = ((polygonIndex >> 3) / 2) & 4095;"),s.push("int v_packed_object_id_index = ((polygonIndex >> 3) / 2) >> 12;"),s.push("ivec3 packedObjectId = ivec3(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).rgb);"),s.push("int objectIndex;"),s.push("if (((polygonIndex >> 3) % 2) == 0) {"),s.push(" objectIndex = (packedObjectId.r << 4) + (packedObjectId.g >> 4);"),s.push("} else {"),s.push(" objectIndex = ((packedObjectId.g & 15) << 8) + packedObjectId.b;"),s.push("}"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("int h_index = polygonIndex & 4095;"),s.push("int v_index = polygonIndex >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = transpose(mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*3+2, objectIndexCoords.y), 0), vec4(0, 0, 0, 1)));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position1 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("vec3 position2 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("vec3 position3 = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(position3 - position1, position2 - position1));"),s.push("int vertexNumber = gl_VertexID % 3;"),s.push("vec3 position;"),s.push("if (vertexNumber == 0) position = position1;"),s.push("else if (vertexNumber == 1) position = position2;"),s.push("else position = position3;"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags2 = flags2.r;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick flat normals fragment shader"),i.push("#extension GL_OES_standard_derivatives : enable"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in int vFlags2;");for(var n=0;n<t.sectionPlanes.length;n++)i.push("uniform bool sectionPlaneActive"+n+";"),i.push("uniform vec3 sectionPlanePos"+n+";"),i.push("uniform vec3 sectionPlaneDir"+n+";")}if(i.push("out vec4 outNormal;"),i.push("void main(void) {"),s){i.push(" bool clippable = vFlags2 > 0;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(n=0;n<t.sectionPlanes.length;n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(" outNormal = vec4((worldNormal * 0.5) + 0.5, 1.0);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ws{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRenderer&&!this._colorQualityRenderer.getValid()&&(this._colorQualityRenderer.destroy(),this._colorQualityRenderer=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._vertexDepthRenderer&&!this._vertexDepthRenderer.getValid()&&(this._vertexDepthRenderer.destroy(),this._vertexDepthRenderer=null),this._vertexDepthZBufferInitializer&&!this._vertexDepthZBufferInitializer.getValid()&&(this._vertexDepthZBufferInitializer.destroy(),this._vertexDepthZBufferInitializer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Vt(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Vt(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRenderer(){return this._colorQualityRenderer||(this._colorQualityRenderer=new ms(this._scene,!1)),this._colorQualityRenderer}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO||(this._colorQualityRendererWithSAO=new ms(this._scene,!0)),this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Qt(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new us(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ps(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Kt(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Xt(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Jt(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new os(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new vs(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new $t(this._scene)),this._pickDepthRenderer}get vertexDepthRenderer(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new ss(this._scene)),this._vertexDepthRenderer}get vertexDepthZBufferInitializer(){return this._vertexDepthZBufferInitializer||(this._vertexDepthZBufferInitializer=new rs(this._scene)),this._vertexDepthZBufferInitializer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ls(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ds(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRenderer&&this._colorQualityRenderer.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._vertexDepthRenderer&&this._vertexDepthRenderer.destroy(),this._vertexDepthZBufferInitializer&&this._vertexDepthZBufferInitializer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const gs={};we.SUPPORTED_EXTENSIONS.OES_element_index_uint;class Ts{constructor(){this.positions=[],this.metallicRoughness=[],this.indices8Bits=[],this.indices16Bits=[],this.indices32Bits=[],this.edgeIndices8Bits=[],this.edgeIndices16Bits=[],this.edgeIndices32Bits=[],this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}
2
2
  /**
3
3
  * @author https://github.com/tmarti, with support from https://tribia.com/
4
4
  * @license MIT